如何在 JavaScript 中逐行读取文本文件?

问题描述 投票:0回答:3

我需要在 JavaScript 中逐行读取文本文件。

我可能想对每一行做一些事情(例如跳过或修改它)并将该行写入另一个文件。但具体操作超出了这个问题的范围。

有很多类似措辞的问题,但大多数实际上是一步将整个文件读入内存,而不是逐行读取。因此这些解决方案不适用于更大的文件。

javascript node.js file-io
3个回答
20
投票

Node.js 在 v18.11.0 中添加了一个新功能来逐行读取文件

  • filehandle.readLines([选项])

这就是您如何将其与您想要阅读的文本文件一起使用

import { open } from 'node:fs/promises';
myFileReader();
async function myFileReader() {
    const file = await open('./TextFileName.txt');
    for await (const line of file.readLines()) {
        console.log(line)
    }
}

要了解更多信息,请阅读 Node.js 文档,这里是文件系统 readlines() 的链接: https://nodejs.org/api/fs.html#filehandlereadlinesoptions


10
投票

逐行读取文本文件的代码确实非常重要且难以发现。

此代码使用 NodeJS 的 readline 模块逐行读写文本文件。它可以处理大文件。

const fs = require("fs");
const readline = require("readline");

const input_path = "input.txt";
const output_path = "output.txt";

const inputStream = fs.createReadStream(input_path);
const outputStream = fs.createWriteStream(output_path, { encoding: "utf8" });
var lineReader = readline.createInterface({
  input: inputStream,
  terminal: false,
});
lineReader.on("line", function (line) {
  outputStream.write(line + "\n");
});


0
投票

这是来自 MDN 文档 的函数,它向您展示如何使用 ReadableStream 逐行读取文件。这与 Node.js 和 Web 浏览器兼容。此示例使用

fetch
,但如果您已经有 File,则可以调用
stream()
getReader()

async function* makeTextFileLineIterator(fileURL) {
  const utf8Decoder = new TextDecoder("utf-8");
  let response = await fetch(fileURL);
  let reader = response.body.getReader();
  let { value: chunk, done: readerDone } = await reader.read();
  chunk = chunk ? utf8Decoder.decode(chunk, { stream: true }) : "";

  let re = /\r\n|\n|\r/gm;
  let startIndex = 0;

  for (;;) {
    let result = re.exec(chunk);
    if (!result) {
      if (readerDone) {
        break;
      }
      let remainder = chunk.substr(startIndex);
      ({ value: chunk, done: readerDone } = await reader.read());
      chunk =
        remainder + (chunk ? utf8Decoder.decode(chunk, { stream: true }) : "");
      startIndex = re.lastIndex = 0;
      continue;
    }
    yield chunk.substring(startIndex, result.index);
    startIndex = re.lastIndex;
  }
  if (startIndex < chunk.length) {
    // last line didn't end in a newline char
    yield chunk.substr(startIndex);
  }
}

for await (let line of makeTextFileLineIterator(urlOfFile)) {
  processLine(line);
}
© www.soinside.com 2019 - 2024. All rights reserved.