使用node.js覆盖文件中的一行

使用node.js覆盖大型文本文件(2MB +)的最佳方法是什么?

我目前的方法涉及

  • 将整个文件复制到缓冲区中。
  • 通过换行符( \n )将缓冲区分割成一个数组。
  • 使用缓冲区索引覆盖该行。
  • 然后在与\n连接后用缓冲区覆盖文件。

首先,你需要search行的起始位置和结束位置。 接下来你需要使用一个函数来replace这一行。 我有使用我的一个库的第一部分的解决scheme: Node-BufferedReader 。

 var lineToReplace = "your_line_to_replace"; var startLineOffset = 0; var endLineOffset = 0; new BufferedReader ("your_file", { encoding: "utf8" }) .on ("error", function (error){ console.log (error); }) .on ("line", function (line, byteOffset){ startLineOffset = endLineOffset; endLineOffset = byteOffset - 1; //byteOffset is the offset of the NEXT byte. -1 if it's the end of the file, if that's the case, endLineOffset = <the file size> if (line === lineToReplace ){ console.log ("start: " + startLineOffset + ", end: " + endLineOffset + ", length: " + (endLineOffset - startLineOffset)); this.interrupt (); //interrupts the reading and finishes } }) .read ();