淺析Node.js查找字符串功能
需求如下:
整個目錄下大概有40幾M,文件無數(shù),由于時間久了, 記不清那個字符串具體在哪個文件,于是。強大,亮瞎雙眼的Node.js閃亮登場:
windows下安裝Node.js和安裝普通軟件毫無差別,裝完后打開Node.js的快捷方式,或者直接cmd,你懂的。
創(chuàng)建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");
}
兩個參數(shù):第一個參數(shù)為“文件夾名稱” 第二個參數(shù)為“你要查找的字符串”
如圖:

打印出文件路徑,完事,收工。速度實在是彪悍,亮瞎雙眼。。。如果采用java全文搜索,你慘了...
Nodejs查找,讀寫文件
(1),路徑處理
1.首先,我們需要注意的文件路徑的規(guī)范化,nodejs給我們提供了Path模塊,normolize方法能幫我們規(guī)范化路徑:
var path = require('path');
path.normalize('/foo/bar/nor/faz/..'); -> /foo/bar/nor
2.當(dāng)然還有join合并路徑:
var path = require('path');
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); ->/foo/bar/baz/asdf
3.解析路徑
var path = require('path');
path.resolve('/foo/bar', './baz'); ->/foo/bar/baz
path.resolve('/foo/bar', '/tmp/file/'); ->/tmp/file
4.在兩個相對路徑間查找相對路徑
var path = require('path');
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); ->../../impl/bbb
5.抽離路徑
var path = require('path');
path.dirname('/foo/bar/baz/asdf/quux.txt'); ->/foo/bar/baz/asdf
=================
var path = require('path');
path.basename('/foo/bar/baz/asdf/quux.html') ->quux.html
甚至你還還可以將后綴名去掉,只需要在basename中傳入第二個參數(shù),參數(shù)為后綴名,例如:
var path = require('path');
path.basename('/foo/bar/baz/asdf/quux.html', '.html'); ->quux
當(dāng)然文件路徑中可能會存在各種不同的文件,我們不可能硬編碼后綴來得到我們想要的結(jié)果,
所以有一個方法能幫我們得到后綴名:
path.extname('/a/b/index.html'); // => '.html'
path.extname('/a/b.c/index'); // => ''
path.extname('/a/b.c/.'); // => ''
path.extname('/a/b.c/d.'); // => '.'
(2),文件處理
var fs = require('fs');
1.判斷文件是否存在
fs.exists(path, function(exists) {});
上面的接口為異步操作的,因此有回調(diào)函數(shù),在回調(diào)中可以處理我們的各種操作,如果需要同步操作可以用下面的方法:
fs.existsSync(path);
2.讀取文件狀態(tài)信息
fs.stat(path, function(err, stats) {
if (err) { throw err;}
console.log(stats);
});
控制臺輸出states的內(nèi)容大致如下:
{ dev: 234881026,
ino: 95028917,
mode: 33188,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
size: 5086,
blksize: 4096,
blocks: 0,
atime: Fri, 18 Nov 2011 22:44:47 GMT,
mtime: Thu, 08 Sep 2011 23:50:04 GMT,
ctime: Thu, 08 Sep 2011 23:50:04 GMT }
同時,stats還具有一些方法,比如:
stats.isFile();
stats.isDirectory();
stats.isBlockDevice();
stats.isCharacterDevice();
stats.isSymbolicLink();
stats.isFifo();
stats.isSocket();
.讀寫文件
fs.open('/path/to/file', 'r', function(err, fd) {
// todo
});
第二個參數(shù)為操作類型:
r : 只讀
r+ : 讀寫
w : 重寫文件
w+ : 重寫文件,如果文件不存在則創(chuàng)建
a : 讀寫文件,在文件末尾追加
a+ : 讀寫文件,如果文件不存在則創(chuàng)建
下面為一個讀取文件的小例子:
var fs = require('fs');
fs.open('./nodeRead.html', 'r', function opened(err, fd) {
if (err) { throw err }
var readBuffer = new Buffer(1024),
bufferOffset = 0,
bufferLength = readBuffer.length,
filePosition = 100;
fs.read(fd,
readBuffer,
bufferOffset,
bufferLength,
filePosition,
function read(err, readBytes) {
if (err) { throw err; }
console.log('just read ' + readBytes + ' bytes');
if (readBytes > 0) {
console.log(readBuffer.slice(0, readBytes));
}
});
});
下面為一個寫文件的小例子:
var fs = require('fs');
fs.open('./my_file.txt', 'a', function opened(err, fd) {
if (err) { throw err; }
var writeBuffer = new Buffer('hello, world!'),
bufferPosition = 0,
bufferLength = writeBuffer.length, filePosition = null;
fs.write( fd,
writeBuffer,
bufferPosition,
bufferLength,
filePosition,
function(err, written) {
if (err) { throw err; }
console.log('wrote ' + written + ' bytes');
});
});
對于文件的讀寫操作,我們不應(yīng)該忘記在這些操作都完成之后執(zhí)行關(guān)閉操作,即close(); 下面是一個封裝的方法,其中就包括了文件的后期關(guān)閉操作,使用起來方便:
var fs = require('fs');
function openAndWriteToSystemLog(writeBuffer, callback) {
fs.open('./my_file', 'a', function(err, fd) {
if (err) { return callback(err); }
function notifyError(err) {
fs.close(fd, function() {
callback(err);
});
}
var bufferOffset = 0,
bufferLength = writeBuffer.length,
filePosition = null;
fs.write( fd, writeBuffer, bufferOffset, bufferLength, filePosition,function(err, written) {
if (err) { return notifyError(err); }
fs.close(fd, function() {
callback(err);
});
});
});
}
openAndWriteToSystemLog(new Buffer('writing this string'),function(err) {
if (err) {
console.log("error while opening and writing:", err.message);
return;
}
console.log('All done with no errors');
});
相關(guān)文章
NestJS核心概念之Middleware中間件創(chuàng)建使用示例
這篇文章主要為大家介紹了NestJS核心概念之Middleware中間件創(chuàng)建使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
node+express框架中連接使用mysql(經(jīng)驗總結(jié))
這篇文章主要介紹了node+express框架中連接使用mysql(經(jīng)驗總結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
這篇文章主要介紹了node中Stream的詳細介紹,流是一個數(shù)據(jù)傳輸手段,是端到端信息交換的一種方式,而且是有順序的,是逐塊讀取數(shù)據(jù)、處理內(nèi)容,用于順序讀取輸入或?qū)懭胼敵?/div> 2022-09-09最新評論

