Home > Web Front-end > JS Tutorial > Node.js implements searching for a certain string and the file it is located in a directory_node.js

Node.js implements searching for a certain string and the file it is located in a directory_node.js

WBOY
Release: 2016-05-16 16:37:48
Original
1617 people have browsed it

The requirements are as follows:

There are about 40 M in the entire directory, and there are countless files. Because it has been a long time, I can’t remember which file the string is in, so. The powerful and blinding Node.js makes its debut.

Installing Node.js under windows is no different from installing ordinary software. After installation, open the shortcut of Node.js, or directly cmd, you know.

Create findString.js

Copy code The code is as follows:

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");
}

Two parameters: the first parameter is "folder name" and the second parameter is "the string you are looking for"

Pictured:

Print out the file path, done, and call it a day. The speed is really fierce and blinding. . . If you use java full text search, you will be in trouble...

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template