使用node.js覆盖文件中的一行 [英] Overwrite a line in a file using node.js
本文介绍了使用node.js覆盖文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的当前方法涉及到$ b $
- 将整个文件复制到一个缓冲区中。
- 用新的行字符(<$ c $
- 使用缓冲区索引覆盖该行
- 然后覆盖文件在加入
\\\
。
解决方案首先,你需要搜索行的起始位置和结束位置。接下来你需要使用一个函数来替换这一行。我有第一部分的解决方案,使用我的一个库: 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);
。)(line,function(line,byteOffset){
startLineOffset = endLineOffset;
endLineOffset = byteOffset - 1; // byteOffset是NEXT byte。-1如果是文件的结尾,如果是这种情况,endLineOffset =<文件大小>
if(line === lineToReplace){
console.log (start:+ startLineOffset +,end:+ endLineOffset +
,length:+(endLineOffset - startLineOffset));
this.interrupt(); //中断读取并结束
}
})
.read();
What's the best way to overwrite a line in a large (2MB+) text file using node.js?
My current method involves
- copying the entire file into a buffer.
- Spliting the buffer into an array by the new line character (
\n
). - Overwriting the line by using the buffer index.
- Then overwriting the file with the buffer after join with
\n
.
解决方案
First, you need to search where the line starts and where it ends. Next you need to use a function for replacing the line. I have the solution for the first part using one of my libraries: 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 ();
这篇关于使用node.js覆盖文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文