Overwrite a line in a file using node.js

Viewed 7542

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.
2 Answers

Maybe you can try the package replace-in-file

suppose we have a txt file as below

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

and we want to replace:

line1 -> line3
line2 -> line4

Then, we can do it like this:

const replace = require('replace-in-file');

const options = {
    files: "./file.txt",
    from: [/line1/g, /line2/g],
    to: ["line3", "line4"]
};

replace(options)
.then(result => {
    console.log("Replacement results: ",result);
})
.catch(error => {
    console.log(error);
});

the result as below:

// file.txt
"line3"
"line4"
"line5"
"line6"
"line3"
"line4"
"line5"
"line6"

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

Related