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.
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))
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加