问题: 我有一个棘手的情况,我正在递归遍历文件和目录,当文件符合特定条件时,我使用 Node 的 readLine(异步函数)读取该文件的第一行。一旦该行被读取,条目就会被插入一个变量(例如 depTree)。由于我的一些代码是异步的,所以我无法同步获取 depTree 的值。
代码:
const fs = require('fs');
const readline = require('readline');
const path = './mycoolpath/';
const depTree = [];
const imports = file => {
const readLines = readline.createInterface({
input: fs.createReadStream(file),
crlfDelay: Infinity
});
// read each line, and push line to depTree if it passes my regex criteria
readLines.on('line', (line) => {
if (/lineMatchesMyregex/.test(line)) {
depTree.push(line)
}
});
}
const recursiveSearch = path => {
const files = fs.readdirSync(path);
for (var i in files) {
var file = path + '/' + files[i];
var stats = fs.statSync(file);
if (stats.isFile()) {
imports(file);
}
else if (stats.isDirectory()) {
recursiveSearch(file);
}
}
};
recursiveSearch(path);
//// embaressing setTimeout
// setTimeout(() => {
// console.log(depTree)
// }, 1000)
尝试:
我不得不使用 setTimeout 并且我确信有更好的方法,我修改了回调和 promise 但无济于事。如果有任何帮助/见解,我将不胜感激。
最佳答案
如果您在 Node.js 中使用 async/await
关键字和 promises,您可以按如下方式解决此问题:
const fs = require('fs');
const readline = require('readline');
const path = './mycoolpath/';
const depTree = [];
const imports = file => {
return new Promise((resolve, reject) => {
const readLines = readline.createInterface({
input: fs.createReadStream(file),
crlfDelay: Infinity
});
// read each line, and push line to depTree if it passes my regex criteria
readLines.on('line', (line) => {
if (/lineMatchesMyregex/.test(line)) {
depTree.push(line)
}
});
// once done reading all the lines, resolve the promise
readLines.on('close', () => {
resolve();
})
});
}
const recursiveSearch = async (path) => {
const files = fs.readdirSync(path);
for (var i in files) {
var file = path + '/' + files[i];
var stats = fs.statSync(file);
if (stats.isFile()) {
await imports(file);
} else if (stats.isDirectory()) {
await recursiveSearch(file);
}
}
};
//// embaressing setTimeout
setTimeout(async () => {
await recursiveSearch(path);
console.log(depTree)
}, 1000)
// or even better, to avoid too long or too short timeout
recursiveSearch(path)
.then(() => {
console.log(depTree)
})
关于javascript - 递归异步到 promise 或回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52651882/