Just building on Shyam Tayal's answer, if you want to replace an entire line matching your string, and not just an exact matching string do the following instead:
fs.readFile(someFile, 'utf8', function(err, data) {
let searchString = 'to replace';
let re = new RegExp('^.*' + searchString + '.*$', 'gm');
let formatted = data.replace(re, 'a completely different line!');
fs.writeFile(someFile, formatted, 'utf8', function(err) {
if (err) return console.log(err);
});
});
The 'm' flag will treat the ^ and $ meta characters as the beginning and end of each line, not the beginning or end of the whole string.
So the above code would transform this txt file:
one line
a line to replace by something
third line
into this:
one line
a completely different line!
third line
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…