我正在尝试打印所有Txt文件的完整路径,其中包含一个特定的字符串。 我怎样才能通过cmd实现节点js?
感谢。
答案 0 :(得分:1)
创建一个或两个包含字符串的文件。
const fs = require("fs");
const path = require("path");
// check if you not passed correct commands
if (process.argv.length < 3) {
console.log("USAGE: node " + " search" + " [EXT]" + " [TEXT]");
process.exit(1);
}
function searchInTxtFiles(ext, str) {
// root directory
const dirPath = path.resolve(__dirname);
// read all the files and filter those files which match with targeted extension like .txt
const fileLists = fs
.readdirSync(dirPath)
.filter(e => path.extname(e).toLowerCase() === "." + ext);
// loop thru the fileLists
return fileLists.map(d => {
return fs.readFile(d, function(err, content) {
if (err) throw err;
// check if the file content has the string that passed from terminal
if (content.indexOf(str) > -1) {
console.log(__dirname + "\\" + d);
} else {
console.log("No file was found");
}
});
});
}
searchInTxtFiles(process.argv[2], process.argv[3]);
// input: node index.js txt lorem
// output: /readfile/data.txt