使用 node.js 覆盖大型 (2MB+) 文本文件中一行的最佳方法是什么?
我目前的方法涉及
- 将整个文件复制到缓冲区中。
- 通过换行符 (
\n
) 将缓冲区拆分为数组。 - 使用缓冲区索引覆盖该行。
- 然后用
\n
连接后用缓冲区覆盖文件。
最佳答案
首先,您需要搜索该行的起点和终点。接下来,您需要使用一个函数来替换该行。我有使用我的一个库的第一部分的解决方案: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 ();
关于javascript - 使用 node.js 覆盖文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692835/