Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
Node Function Returning Empty Array

In the following node function, it is returning an empty array. Not sure why its doing that. Could this be a async await issue? Would appreciate any help. Thank you

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...`)
})
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

getCircuitAndFuse must return Promise like this:

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`
});

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another alternative to Faruk's answer would be to just use fs.readFileSync instead of wrapping your function in a promise and requiring some of that extra ceremony. Using fs.readFileSync will ensure that your function doesn't return prematurely.

Here is your code rewritten with that in mind:

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);
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda