我如何知道带有异步fs.readdir的递归函数何时完成执行? 这里的完整执行意味着将处理给定目录中的所有文件。
我尝试返回一个Promise,并且还使用async / await进行后处理。
var func = (dirName) => {
fs.readdir(dirName, (err, files) => {
files.forEach(file => {
console.log('Total Size = ' + size);
console.log('Size Processed = ' + fileSizeProcessed);
console.log('Processing : ' + file);
var currentDir = path.join(dirName, file).toString();
if ((fs.statSync((currentDir)).isDirectory())) {
func(currentDir);
}
else {
//Process File
}
})
});
}
答案 0 :(得分:1)
您可以将执行包装在Promise中,然后可以等待递归调用被处理,如果使用for,则可以在函数的上下文中停止执行。最后,在处理完所有文件后,我们通过通知一切都已解决来解决最终承诺。
const fs = require('fs')
const path = require('path')
const walk = dirName => {
return new Promise((resolve, reject) => {
fs.readdir(dirName, async (err, files) => {
if (err) {
return reject(err)
}
for (const file of files) {
console.log(`Processing : ${file}`)
const currentDir = path.join(dirName, file)
if ((fs.statSync((currentDir)).isDirectory())) {
await walk(currentDir)
} else {
console.log(`File ${file} processed`)
}
}
resolve(`Folder ${dirName} processed, work finished`)
})
})
}
walk('./walk').then(response => console.log(response))
例如,在以下目录结构中:
如果执行上述代码,则输出如下:
Processing : file1.txt
File file1.txt processed
Processing : file2.txt
File file2.txt processed
Processing : file3.txt
File file3.txt processed
Processing : walk-sub1
Processing : walk-sub1-1
Processing : walk-sub1-1-file1.txt
File walk-sub1-1-file1.txt processed
Processing : walk-sub1-file1.txt
File walk-sub1-file1.txt processed
Processing : walk-sub1-file2.txt
File walk-sub1-file2.txt processed
Processing : walk-sub2
Processing : walk-sub2-file1.txt
File walk-sub2-file1.txt processed
Folder ./walk processed, work finished
请记住要处理内部承诺中的错误,我并不是为了简化示例