En la siguiente función de nodo, devuelve una matriz vacía. No estoy seguro de por qué está haciendo eso. ¿Podría ser un problema de espera asíncrona? Agradecería cualquier ayuda. Gracias
const folderPath = '/public/home.html' function getCircuitAndFuse(folderPath){ //List containing circuit name with its fuse let temporaryList = []; let finalCircuitAndFuseList = [] fs.readFile(__dirname + folderPath, (error, data)=>{ if(error){ console.log(`Unable to read file: ${error}`) }else{ var $ = cheerio.load(data) $('img').each(function(index, element){ let getClassAtr = element.attribs.class temporaryList.push(getClassAtr.slice(0, getClassAtr.lastIndexOf(" "))) }) finalCircuitAndFuseList = [...new Set(temporaryList)] } }) return finalCircuitAndFuseList; } let getInfo = getCircuitAndFuse(folderPath) // Returning empty array console.log(getInfo)
***Server code**** const server = http.createServer(function(req, res){ res.writeHead(200, {'Content-Type': 'text/plain'}) res.end() }).listen(port, ()=>{ console.log(`Server listening on port ${port}. Press Ctrl-C to terminate...`) })
getCircuitAndFuse
debe devolver Promise
así:
function getCircuitAndFuse(folderPath) { return new Promise((resolve, reject) => { //List containing circuit name with its fuse let temporaryList = []; fs.readFile(__dirname + folderPath, (error, data) => { if (error) { console.log(`Unable to read file: ${error}`); } else { var $ = cheerio.load(data); $('img').each(function (index, element) { let getClassAtr = element.attribs.class; temporaryList.push( getClassAtr.slice(0, getClassAtr.lastIndexOf(' ')) ); }); resolve([...new Set(temporaryList)]); } }); }); } getCircuitAndFuse(folderPath).then((getInfo) => { // do something with `getInfo` });
Otra alternativa a la respuesta de Faruk sería simplemente usar fs.readFileSync
en lugar de envolver su función en una promesa y requerir algo de esa ceremonia adicional. El uso fs.readFileSync
garantizará que su función no regrese prematuramente.
Aquí está su código reescrito con eso en mente:
function getCircuitAndFuse(folderPath) { try { let temporaryList = []; const data = fs.readFileSync(__dirname + folderPath); const $ = cheerio.load(data); $("img").each(function (index, element) { let getClassAtr = element.attribs.class; temporaryList.push(getClassAtr.slice(0, getClassAtr.lastIndexOf(" "))); }); return [...new Set(temporaryList)]; } catch (error) { console.log(error); } }