栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在NodeJS中读取文件的第N行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在NodeJS中读取文件的第N行

具有可读流

var fs = require('fs');function get_line(filename, line_no, callback) {    var stream = fs.createReadStream(filename, {      flags: 'r',      encoding: 'utf-8',      fd: null,      mode: 0666,      bufferSize: 64 * 1024    });    var fileData = '';    stream.on('data', function(data){      fileData += data;      // The next lines should be improved      var lines = fileData.split("n");      if(lines.length >= +line_no){        stream.destroy();        callback(null, lines[+line_no]);      }    });    stream.on('error', function(){      callback('Error', null);    });    stream.on('end', function(){      callback('File end reached without finding line', null);    });}get_line('./file.txt', 1, function(err, line){  console.log('The line: ' + line);})

直接解决方案:

您应该使用slice方法而不是循环。

var fs = require('fs');function get_line(filename, line_no, callback) {    var data = fs.readFileSync(filename, 'utf8');    var lines = data.split("n");    if(+line_no > lines.length){      throw new Error('File end reached without finding line');    }    callback(null, lines[+line_no]);}get_line('./file.txt', 9, function(err, line){  console.log('The line: ' + line);})

for(var l in lines)不是遍历数组的最有效方法,您应该这样做:

for(var i = 0, iMax = lines.length; i < iMax; i++){ }

异步方式:

var fs = require('fs');function get_line(filename, line_no, callback) {    fs.readFile(filename, function (err, data) {      if (err) throw err;      // Data is a buffer that we need to convert to a string      // Improvement: loop over the buffer and stop when the line is reached      var lines = data.toString('utf-8').split("n");      if(+line_no > lines.length){        return callback('File end reached without finding line', null);      }      callback(null, lines[+line_no]);    });}get_line('./file.txt', 9, function(err, line){  console.log('The line: ' + line);})



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636424.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号