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

在node.js中一次读取一行文件?

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

在node.js中一次读取一行文件?

从Node.js v0.12和Node.jsv4.0.0开始,有一个稳定的readline核心模块。这是从文件中读取行的最简单方法,而无需任何外部模块:

const fs = require('fs');const readline = require('readline');async function processLineByLine() {  const fileStream = fs.createReadStream('input.txt');  const rl = readline.createInterface({    input: fileStream,    crlfDelay: Infinity  });  // Note: we use the crlfDelay option to recognize all instances of CR LF  // ('rn') in input.txt as a single line break.  for await (const line of rl) {    // Each line in input.txt will be successively available here as `line`.    console.log(`Line from file: ${line}`);  }}processLineByLine();

或者:

var lineReader = require('readline').createInterface({  input: require('fs').createReadStream('file.in')});lineReader.on('line', function (line) {  console.log('Line from file:', line);});

即使没有final,也可以正确读取最后一行(从Node v0.12或更高版本开始)

n

更新
:此示例已添加到Node的API官方文档中。



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

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

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