Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Espere hasta que se complete toda la función

Escribí un código usando alguna promesa, en mi caso, este es un script de conversión que cargará archivos y archivos adjuntos cuando se conviertan. La parte de conversión funciona bien, veo los resultados esperados en el portal xwiki.

Lo que quiero es recorrer los archivos de un directorio, hacer algunas conversiones y buscar y recopilar todos los nombres de imágenes en el archivo. Después de hacer esto, primero necesito cargar la página porque eso es obligatorio en el lado de xwiki y luego quiero cargar los archivos adjuntos. En este momento está cargando los archivos adjuntos incorrectos, en lugar del archivo, los está cargando desde otro archivo. El nombre de archivo tanto en uploadImage como en uploapPage es la página a la que se está cargando.

 function importDirToXWiki (filePath: string, imagePath: string){ fs.readdir(filePath, (err, files) => { if (err){ console.log(err); } files.forEach(file => { convertFile(space, filePath, imagePath, file); }); }); }; function convertFile(directory: string, path: string, imagePath: string, filename: string){ fs.readFile(path + "/" + filename, async function(err: any, data: { toString: () => string; }) { if(err) throw err; attachments = [] //Split the lines let lines = data.toString().replace(/\r\n/g,'\n').split('\n'); //Convert md to xwiki format lines = convertHeaders(lines); lines = convertLists(lines); lines.map(function (line, i) { let filename = extractUsingRegex(line, /([a-zA-Z0-9\s_\\.\-\(\):])+(.png|.jpg)/gm) if(filename.length > 0) attachments.push(filename); lines[i] = convertImageTags(line); }); //Adding HTML support & keep XWiki format active lines.unshift('{{html wiki="true"}}'); lines.push("{{/html}}"); await postNewPage(lines.join("\n"), directory, formatFileName(filename)) Promise.all(attachments.map(async attachment => { await uploadImage(directory, formatFileName(filename), imagePath, attachment) })) }); }; async function uploadImage(space: string, page: string, imagePath: string, filename: string){ if(fs.existsSync(imagePath + "/" + filename)){ let file = fs.readFileSync(imagePath + "/" + filename); await postNewAttachment(file, space, page, filename ); } };
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Puede usar la API fs/promises de Node para simplificar las cosas.

También limpié algunos usos no idiomáticos de .forEach vs .map . Sin darse cuenta, también estaba haciendo que attachments fueran globales (sin const o var ); considere un linter como ESLint para advertirle sobre cosas como esa.

 const fsp = require("fs/promises"); async function importDirToXWiki(filePath: string, imagePath: string) { const files = await fsp.readdir(filePath); const conversionPromises = files.map((file) => convertFile(space, filePath, imagePath, file)); return Promise.all(conversionPromises); } async function convertFile(directory: string, path: string, imagePath: string, filename: string) { const data = await fsp.readFile(path + filename, "utf8"); const attachments = []; //Split the lines let lines = data.toString().replace(/\r\n/g, "\n").split("\n"); //Convert md to xwiki format lines = convertHeaders(lines); lines = convertLists(lines); lines = lines.map(function (line) { let filename = extractUsingRegex(line, /([a-zA-Z0-9\s_\\.\-\(\):])+(.png|.jpg)/gm); if (filename.length > 0) attachments.push(filename); return convertImageTags(line); }); //Adding HTML support & keep XWiki format active lines.unshift('{{html wiki="true"}}'); lines.push("{{/html}}"); await postNewPage(lines.join("\n"), directory, formatFileName(filename)); const uploadPromises = attachments.map((attachment) => uploadImage(directory, formatFileName(filename), imagePath, attachment), ); return Promise.all(uploadPromises); } async function uploadImage(space: string, page: string, imagePath: string, filename: string) { let data; try { const data = await fsp.readFile(imagePath + filename); return await postNewAttachment(data, space, page, filename); } catch (err) { if (err.code === "ENOENT") { return; // "Not found", that's likely benign } throw err; } }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda