Node.js filehandle.readLines() 方法

Node.js filehandle.readLines() 方法

Node.js 是一个开源的服务器端运行环境。读取和写入是任何应用程序的两个主要重要功能。Node.js提供了一系列内置的功能来执行读取和写入操作。fs 包含了执行文件操作所需的函数。

filehandle.readLines() 是Node.js中的一个内置函数。该函数逐行从文件中读取内容。

语法:

filehandle.readLines();
JavaScript

参数: 该函数没有任何参数。

返回值: 该函数返回readline.InterfaceConstructor。

注: 在运行此程序之前,请将此文本添加到gfg.txt文件中。

Hey GeekforGeeks
A computer science portal for geeks
JavaScript

示例1: 在这个示例中,我们将看到 filehandle.readLines() 函数。

const { open } = require('node:fs/promises'); 
  
(async () => { 
    const file = await open('./gfg.txt'); 
  
    for await (const line of file.readLines()) { 
        if (line.includes('science')) { 
            console.log(line); 
        } 
    } 
})();
JavaScript

输出:

Node.js filehandle.readLines() 方法

示例2: 在这个程序中,我们将使用不同的方法进行操作。

const { open } = require('node:fs/promises'); 
  
(async () => { 
    const file = await open('./gfg.txt'); 
    let scienceLines = 0; 
    let nonScienceLines = 0; 
    let searchVariable = "gfg"; 
  
    for await (const line of file.readLines()) { 
        if (line.includes(searchVariable)) { 
            scienceLines++; 
        } else { 
            nonScienceLines++; 
        } 
    } 
  
    console.log(`Number of lines containing  
        {searchVariable}:{scienceLines}`); 
    console.log(`Number of lines not containing  
        {searchVariable}:{nonScienceLines}`); 
})();
JavaScript

输出:

Node.js filehandle.readLines() 方法

结论: filehandle.readLines() 函数用于逐行读取Node.js中的文件,返回一个可异步迭代的对象,方便对文件的每一行进行迭代。通过使用 filehandle.readLines() ,开发者可以轻松处理大型文件的每一行,实现高效的数据处理,避免一次性将整个文件加载到内存中。这在处理无法完全放入内存的大文件或以非阻塞方式异步处理文件时特别有用。

参考资料 : https://nodejs.org/api/fs.html#filehandlereadlinesoptions

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册