13

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!

user4986573
  • 163
  • 2
  • 5

1 Answers1

6

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.

Norfeldt
  • 8,272
  • 23
  • 96
  • 152
Dale
  • 69
  • 1
  • 6
  • 1
    Solution given in another question is also helpful https://stackoverflow.com/a/30764806/713573 – Gagan Nov 26 '20 at 09:53