Node.js实现在目录中查找某个字符串及所在文件_node.js
程序员文章站
2022-05-05 11:21:32
...
需求如下:
var path = require("path");
var fs = require("fs");
var filePath = process.argv[2];
var lookingForString = process.argv[3];
recursiveReadFile(filePath);
function recursiveReadFile(fileName){
if(!fs.existsSync(fileName)) return;
if(isFile(fileName)){
check(fileName);
}
if(isDirectory(fileName)){
var files = fs.readdirSync(fileName);
files.forEach(function(val,key){
var temp = path.join(fileName,val);
if(isDirectory(temp)) recursiveReadFile(temp);
if (isFile(temp)) check(temp);
})
}
}
function check(fileName){
var data = readFile(fileName);
var exc = new RegExp(lookingForString);
if(exc.test(data))
console.log(fileName);
}
function isDirectory(fileName){
if(fs.existsSync(fileName)) return fs.statSync(fileName).isDirectory();
}
function isFile(fileName){
if(fs.existsSync(fileName)) return fs.statSync(fileName).isFile();
}
function readFile(fileName){
if(fs.existsSync(fileName)) return fs.readFileSync(fileName,"utf-8");
}
两个参数:第一个参数为“文件夹名称” 第二个参数为“你要查找的字符串”
整个目录下大概有40几M,文件无数,由于时间久了, 记不清那个字符串具体在哪个文件,于是。强大,亮瞎双眼的Node.js闪亮登场。
windows下安装Node.js和安装普通软件毫无差别,装完后打开Node.js的快捷方式,或者直接cmd,你懂的。
创建findString.js
复制代码 代码如下:
var path = require("path");
var fs = require("fs");
var filePath = process.argv[2];
var lookingForString = process.argv[3];
recursiveReadFile(filePath);
function recursiveReadFile(fileName){
if(!fs.existsSync(fileName)) return;
if(isFile(fileName)){
check(fileName);
}
if(isDirectory(fileName)){
var files = fs.readdirSync(fileName);
files.forEach(function(val,key){
var temp = path.join(fileName,val);
if(isDirectory(temp)) recursiveReadFile(temp);
if (isFile(temp)) check(temp);
})
}
}
function check(fileName){
var data = readFile(fileName);
var exc = new RegExp(lookingForString);
if(exc.test(data))
console.log(fileName);
}
function isDirectory(fileName){
if(fs.existsSync(fileName)) return fs.statSync(fileName).isDirectory();
}
function isFile(fileName){
if(fs.existsSync(fileName)) return fs.statSync(fileName).isFile();
}
function readFile(fileName){
if(fs.existsSync(fileName)) return fs.readFileSync(fileName,"utf-8");
}
两个参数:第一个参数为“文件夹名称” 第二个参数为“你要查找的字符串”
如图:
打印出文件路径,完事,收工。速度实在是彪悍,亮瞎双眼。。。如果采用java全文搜索,你惨了...