使用 readFile 将文件读入数组时如何修复 "undefined" 数组
How to fix "undefined" array when reading a file into an array with readFile
我正在尝试将文本文件中的文件名列表加载到 js 数组中。
我尝试使用 fs 模块来执行此操作,虽然我可以在 readFile 函数内成功打印数组,但如果我 return 数组并尝试在外部打印它,我就无法这样做。
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);
文件中的文件名应输出为字符串数组。但现在它只打印 undefined
。我认为这与readFile是异步的事实有关,但我不确定如何解决它。
使用readFileSync
会容易很多,因为名称中的Sync
表示它是一个同步操作:
function parseFileList(fileToRead) [
const textByLine = fs.readFileSync(fileToRead, "utf8").split("\n").slice(0, -1);
return textByLine;
}
那是因为您正在回调中收到响应。如果你想让这个函数起作用,你必须把它转换成一个 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);
});
})
}
现在您可以像这样使用它:
parseFileList(filename).then(data => console.log(data))
我正在尝试将文本文件中的文件名列表加载到 js 数组中。
我尝试使用 fs 模块来执行此操作,虽然我可以在 readFile 函数内成功打印数组,但如果我 return 数组并尝试在外部打印它,我就无法这样做。
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);
文件中的文件名应输出为字符串数组。但现在它只打印 undefined
。我认为这与readFile是异步的事实有关,但我不确定如何解决它。
使用readFileSync
会容易很多,因为名称中的Sync
表示它是一个同步操作:
function parseFileList(fileToRead) [
const textByLine = fs.readFileSync(fileToRead, "utf8").split("\n").slice(0, -1);
return textByLine;
}
那是因为您正在回调中收到响应。如果你想让这个函数起作用,你必须把它转换成一个 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);
});
})
}
现在您可以像这样使用它:
parseFileList(filename).then(data => console.log(data))