简体   繁体   中英

How to fix "undefined" array when reading a file into an array with readFile

I'm trying to load a list of filenames in a text file into a js array.

I tried using the fs module to do this and while I can successfully print the array inside the readFile function, I cannot do so if I return the array and try to print it outside.

const fs = require("fs");
function parseFileList(fileToRead){

    fs.readFile(fileToRead, 'utf8', (err, data) => {
        if (err) throw err;
        const textByLine = data.split("\n").slice(0,-1);
        return textByLine;
    });
}

const refList = parseFileList(argv.ref);
console.log(refList);

The filenames in the file should output as an array of strings. But right now it just prints undefined . I think this has something to do with the fact that readFile is async, but I'm not sure how to resolve it.

It'd be a lot easier to use readFileSync because the Sync in the name indicates that it is a synchronous operation:

function parseFileList(fileToRead) [
  const textByLine = fs.readFileSync(fileToRead, "utf8").split("\n").slice(0, -1);
  return textByLine;
}

That's because you are getting a response in callback. if you want to make this function work, you have to convert it into a Promise:

function parseFileList(fileToRead){
    return new Promise((resolve, reject) => {
     fs.readFile(fileToRead, 'utf8', (err, data) => {
        if (err) reject(err);
        const textByLine = data.split("\n").slice(0,-1);
        return resolve(textByLine);
     });
    })

}

Now you can use it like:

parseFileList(filename).then(data => console.log(data))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM