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('------'); }
相关文章推荐
- Node.js 读取TXT文件内容 fs.readFile()
- 【Node.js】'readline' 逐行读取、写入文件内容
- node.js实现逐行读取文件内容的代码
- Node.js readline 逐行读取、写入文件内容的示例
- 【Node.js】'readline' 逐行读取、写入文件内容
- Node.js中读取TXT文件内容fs.readFile()用法
- node.js 读取文件内容
- node.js实现逐行读取文件内容的代码
- Node.js读取文件内容
- node.js 读取zip中文件内容
- Node.js读取文件内容示例
- node.js使用readline按行读取文件内容
- node.js实现逐行读取文件内容的代码
- node.js 读取文件--createReadStream
- Node.Js Buffer类(缓冲区)-(三)文件读取实例
- node.js抓取并分析网页内容有无特殊内容的js文件
- node.js(4)异步式I/O与事件式编程 nodejs文件读取
- 详解Node.js读写中文内容文件操作
- Node.js 读取文件
- Node.js环境中同步分行读取文件