How can I change a specific line in a file with node js?

8.3k views Asked by At

I want to change a specific line in a text file using node js with the fs module.

Is there a more elegant way then loading the file into an array?

Old File:

Line 1
Line 2
Line 3

New File:

Line 1
something new
Line 3

Thanks for your replies!

1

There are 1 answers

1
Dale On

Try using this:

var fs = require('fs')
fs.readFile("your file", {encoding: 'utf8'}, function (err,data) {
    var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');
fs.writeFile("your file", formatted, 'utf8', function (err) {
    if (err) return console.log(err);
 });
});

If this doesn't work, visit https://www.npmjs.com/package/replace-in-file.