因为问题中没有包含所有内容,所以我做了一个假设:
我们正在寻找完整的单词(如果不是这样,请将正则表达式替换为简单的indexOf())。
现在,我将代码拆分为两个函数 - 使其更具可读性和更易于递归查找文件。
同步版本:
const path = require('path');
const fs = require('fs');
function searchFilesInDirectory(dir, filter, ext) {
if (!fs.existsSync(dir)) {
console.log(`Specified directory: ${dir} does not exist`);
return;
}
const files = getFilesInDirectory(dir, ext);
files.forEach(file => {
const fileContent = fs.readFileSync(file);
// We want full words, so we use full word boundary in regex.
const regex = new RegExp('\\b' + filter + '\\b');
if (regex.test(fileContent)) {
console.log(`Your word was found in file: ${file}`);
}
});
}
// Using recursion, we find every file with the desired extention, even if its deeply nested in subfolders.
function getFilesInDirectory(dir, ext) {
if (!fs.existsSync(dir)) {
console.log(`Specified directory: ${dir} does not exist`);
return;
}
let files = [];
fs.readdirSync(dir).forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.lstatSync(filePath);
// If we hit a directory, apply our function to that dir. If we hit a file, add it to the array of files.
if (stat.isDirectory()) {
const nestedFiles = getFilesInDirectory(filePath, ext);
files = files.concat(nestedFiles);
} else {
if (path.extname(file) === ext) {
files.push(filePath);
}
}
});
return files;
}
异步版本 - 因为async 很酷:
const path = require('path');
const fs = require('fs');
const fsReaddir = util.promisify(fs.readdir);
const fsReadFile = util.promisify(fs.readFile);
const fsLstat = util.promisify(fs.lstat);
async function searchFilesInDirectoryAsync(dir, filter, ext) {
const files = await fsReaddir(dir).catch(err => {
throw new Error(err.message);
});
const found = await getFilesInDirectoryAsync(dir, ext);
for (file of found) {
const fileContent = await fsReadFile(file);
// We want full words, so we use full word boundary in regex.
const regex = new RegExp('\\b' + filter + '\\b');
if (regex.test(fileContent)) {
console.log(`Your word was found in file: ${file}`);
}
};
}
// Using recursion, we find every file with the desired extention, even if its deeply nested in subfolders.
async function getFilesInDirectoryAsync(dir, ext) {
let files = [];
const filesFromDirectory = await fsReaddir(dir).catch(err => {
throw new Error(err.message);
});
for (let file of filesFromDirectory) {
const filePath = path.join(dir, file);
const stat = await fsLstat(filePath);
// If we hit a directory, apply our function to that dir. If we hit a file, add it to the array of files.
if (stat.isDirectory()) {
const nestedFiles = await getFilesInDirectoryAsync(filePath, ext);
files = files.concat(nestedFiles);
} else {
if (path.extname(file) === ext) {
files.push(filePath);
}
}
};
return files;
}
如果您还没有使用/理解 async/await,那么尽快采取并学习它是一个很好的步骤。相信我,你会喜欢不再看到那些丑陋的回调!
更新:
正如您在 cmets 中指出的那样,您希望它在对文件运行 node 进程后执行该函数。您还希望将函数参数作为node 的参数传递。
为此,您需要在文件末尾添加:
searchFilesInDirectory(process.argv[2], process.argv[3], process.argv[4]);
这会提取我们的参数并将它们传递给函数。
这样,您可以像这样调用我们的流程(示例参数):
node yourscriptname.js ./ james .txt
就个人而言,如果我要写这篇文章,我会利用异步代码的美感,以及 Node.js 的 async / await。
附带说明:
如果您添加正确的格式,您可以轻松提高代码的可读性。不要误会我的意思,这并不可怕 - 但可以改进:
- 在逗号后使用空格或换行符。
- 在等式运算符和算术运算符周围使用空格。
只要格式一致,一切看起来都会好很多。