Overwrite a line in a file using node.js

前端 未结 2 1409
独厮守ぢ
独厮守ぢ 2020-12-03 18:22

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.
相关标签:
2条回答
  • 2020-12-03 18:45

    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 ();
    
    0 讨论(0)
  • 2020-12-03 18:47

    Maybe you can try the package replace-in-file

    suppose we have a txt file as below, and we want to replace:

    line1 -> line3

    line2 -> line4

    // file.txt
    "line1"
    "line2"
    "line5"
    "line6"
    "line1"
    "line2"
    "line5"
    "line6"
    

    Then, we can do it like this:

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

    More details please refer to its docs: https://www.npmjs.com/package/replace-in-file

    0 讨论(0)
提交回复
热议问题