您的位置:首页 > Web前端 > Node.js

node.js 读取文件内容

2013-12-04 10:29 746 查看
 

//该例子是在windows系统下面跑的
var fs = require('fs');
//如果地址是下面定义的这种方式是无法找到的,他会默认去找Node.js安装路径下的文件,如果没有回报错
//var path="d:\hb.txt";
//如果将路径的分隔符改为"/"则可以找到
var path="d:/hb.txt";
var fileSize;
var file = fs.readFileSync(path, "utf8");
//打印文件的内容
console.log(file);

  

备注:上面的例子我是以文本字符测试的,没有测试二进制

 

 下面这个例子摘抄至  http://www.jiangkunlun.com/2011/11/node-js_read/

//File System
var fs = require('fs');
//fd is the file descriptor used by the WriteStream.
var logFd;
//日志文件
var log = "D:/hb.txt";
//读取过程需要的
var buf,
logSize,
start = 0,
length,
offse = 0,
logArr = '',
LENGHT = 1024 * 1024;//每次读取的长度,1M

//读取文件信息,获取文件长度
fs.stat(log, function(err, stats){
if(err) throw err;
//	console.log(JSON.stringify(stats));
logSize = stats.size;
//打开文件
fs.open(log, 'r', 0666, function(err, fd){
if(err) throw err;
logFd = fd;
length = LENGHT < (logSize - offse) ? LENGHT : (logSize - offse);
buf = new Buffer(length);
//日志读取
readLog();
});
});
//日志读取
function readLog(){
//读取
fs.read(logFd, buf, start, length, offse, function(err){
if(err) throw err;
//按行切分
logArr = buf.toString('utf8').split('\n');
var last = false;
//判断是否是最后一次调用
if(offse + length < logSize){
//最后一行不完整,抛掉,下次在取
last = logArr.pop();
}
//调用日志分析模块,对logArr做处理
logAnalysis();
//处理参数,准备下次调用
if(last !== false){
offse += length - last.length;
length = LENGHT < (logSize - offse) ? LENGHT : (logSize - offse);
buf = new Buffer(length);
//递归读取
if(!lastRead){
readLog();
}
}
});
}
//日志分析模块
function logAnalysis(){
//TODO:日志分析与读取......
console.log(logArr.length);
console.log(logArr[0]);
console.log(logArr[logArr.length - 1]);
console.log('------');
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: