Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - Overwrite a line in a file using node.js

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 ( ).
  • Overwriting the line by using the buffer index.
  • Then overwriting the file with the buffer after join with .
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...