node.js readline 和 line-reader 读取行文件
读取行文件的能力使我们能够读取大文件,而无需将它们全部存储在内存中。这有助于节省资源并提高应用程序的性能。
它允许我们搜索必要的信息,当找到相关信息时,我们可以停止搜索过程,这样可以避免不必要的内存使用。
我们将使用 Readline 模块和 Reader-Module 来实现此目的。
如何阅读1
使用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.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);
});

方法 2 行读取器
使用行读取器模块:行读取器模块是 Node.js 中的一个开源模块,用于读取行文件。它不是原生模块,因此需要使用 npm(节点包管理器)安装它,使用命令:
npm install line-reader --save
行读取器模块提供了perline()方法来读取行文件。
它有一个回调函数,它接受两个参数:该行的内容和一个布尔值,该布尔值存储读取的行是否是文件的最后一行。
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);
});
问题:

版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
上一篇:node.js 读取命令行参数 下一篇:TypeScript 文件的命令行执行
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。