使用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 ();
也许您可以尝试打包replace-in-file
假设我们有一个如下的txt文件,我们要替换:
第1行->第3行
第2行->第4行
// file.txt
"line1"
"line2"
"line5"
"line6"
"line1"
"line2"
"line5"
"line6"
然后,我们可以这样做:
const replace = require('replace-in-file');
const options = {
files: "./file.txt",
from: [/path1/g, /path2/g],
to: ["path3", "path4"]
};
replace(options)
.then(result => {
console.log("Replacement results: ",result);
})
.catch(error => {
console.log(error);
});
更多详细信息,请参阅其文档:https://www.npmjs.com/package/replace-in-file