我有任意数量的文件路径作为字符串存储在数组中。
我需要连续读取这些文件(即在开始读取下一个文件之前完成读取一个文件),并在每个文件读取后输出文件长度。读取完所有文件后,打印 'done'
。
我只能使用 fs.readFile
和 native Javascript。不允许使用 fs.readFileSync
或任何其他模块。另外,我使用的是 Node v6,因此无法使用 async/await。
有没有办法在遵循约束的情况下实现该功能?
最佳答案
你不需要任何花哨的东西,比如 promise 、异步/等待、生成器来实现这一点。
function readAllFiles(list) {
if(list.length == 0) return
console.log('reading ', list[0])
return fs.readFile(list[0], function (err, file) {
if (err) console.error(err); // report the error and continue
console.log('list[0] length:', file.length); // report the file length
readAllFiles(list.slice(1, list.length))
})
}
var l = ['1', 'foo', 'bar']
readAllFiles(l)
关于javascript - 在 Node 中使用 fs.readFile 串联读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832576/