nodejs读取文件、按行读取

1.直接读取

//引入 var fs = require('fs');var path = 'text.json'; fs.readFile(path, function (error, data) { if (error) { console.log('读取文件失败了'+error) } else { data = https://www.it610.com/article/JSON.parse(data.toString()); } })

【nodejs读取文件、按行读取】2.按行读取
//引入 var fs = require('fs'); var readline = require('readline'); //调用方法 var path = 'text.json'; read_file(path,function (data) { console.log(data); }); //定义读取方法 function read_file(path,callback){ var fRead = fs.createReadStream(path); var objReadline = readline.createInterface({ input:fRead }); var arr = new Array(); objReadline.on('line',function (line) { console.log(line) arr.push(JSON.parse(line)); }); objReadline.on('close',function () { callback(arr); }); }

    推荐阅读