Home > Enterprise >  Node Function Returning Empty Array
Node Function Returning Empty Array

Time:09-22

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

CodePudding user response:

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

CodePudding user response:

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);
  }
}
  • Related