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

Carmen ·
更新时间:2024-09-21
· 477 次阅读

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

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

我们将使用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); });

方法二 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逐行读取文件方法请查看下面的相关链接



reader 方法 node

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章