iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >node.jsreadline和line-reader逐行读取文件方法
  • 789
分享到

node.jsreadline和line-reader逐行读取文件方法

摘要

逐行读取文件的能力允许我们读取大文件,而无需将其全部存储到内存中。它有助于节省资源和提高应用程序的效率。 它允许我们寻找所需的信息,一旦找到了相关的信息,我们可以停止搜索过程,可以防

逐行读取文件的能力允许我们读取大文件,而无需将其全部存储到内存中。它有助于节省资源和提高应用程序的效率。

它允许我们寻找所需的信息,一旦找到了相关的信息,我们可以停止搜索过程,可以防止不必要的内存使用。

我们将使用Readline模块和Line-Reader模块来实现这一目标。

方法一 readline

使用Readline模块:Readline是node的原生模块。它是专门为从任何可读流逐行读取内容而开发的。它可用于从命令行读取数据。

因为模块是Node的本机模块。js,它不需要任何安装,可以直接导入:

const readline = require('readline');

因为readline模块只适用于可读流,所以我们需要首先使用fs模块创建可读流。

const file = readline.createInterface({
    input: fs.createReadStream('source_to_file'),
    output: process.stdout,
    terminal: false
});

现在,监听file对象上的line事件。每当从流中读取新行时,事件就会触发:

file.on('line', (line) => {
    console.log(line);
});

例:


// Importing the Required Modules 
const fs = require('fs'); 
const readline = require('readline'); 
  
// Creating a readable stream from file 
// readline module reads line by line  
// but from a readable stream only. 
const file = readline.createInterface({ 
    input: fs.createReadStream('gfg.txt'), 
    output: process.stdout, 
    terminal: false
}); 
  
// Printing the content of file line by 
//  line to console by listening on the 
// line event which will triggered 
// whenever a new line is read from 
// the stream 
file.on('line', (line) => { 
    console.log(line); 
});

node.js readline和line-reader逐行读取文件

方法二 line-reader

使用line-reader模块:line-reader模块是node.js中逐行读取文件的开源模块。它不是本地模块,所以你需要使用npm(节点包管理器)安装它,使用命令:

npm install line-reader --save

行读取器模块提供了逐行读取文件的eachLine()方法。

它有一个回调函数,该函数有两个参数:行内容和一个布尔值,该值存储是否读取的行是文件的最后一行。

const lineReader = require('line-reader');

lineReader.eachLine('source-to-file', (line, last) => {
    console.log(line);
});

例:

// Importing required libraries 
const lineReader = require('line-reader'); 
  
// eachLine() method call on gfg.txt 
// It Got a callback function 
// Printing content of file line by line 
// on the console 
lineReader.eachLine('gfg.txt', (line, last) => { 
    console.log(line); 
}); 

输出:

node.js readline和line-reader逐行读取文件

更多关于node.js readline和line-reader逐行读取文件方法请查看下面的相关链接

--结束END--

本文标题: node.jsreadline和line-reader逐行读取文件方法

本文链接: https://www.lsjlt.com/news/169435.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作