Replace a line in txt file using JavaScript

萝らか妹 提交于 2020-06-13 00:35:52

问题


I am trying to simply replace a line in a text file using JavaScript.

The idea is:

var oldLine = 'This is the old line';
var newLine = 'This new line replaces the old line';

Now i want to specify a file, find the oldLine and replace it with the newLine and save it.

Anyone who can help me here?


回答1:


This should do it

var fs = require('fs')
fs.readFile(someFile, 'utf8', function (err,data) {

  var formatted = data.replace(/This is the old line/g, 'This new line replaces the old line');

 fs.writeFile(someFile, formatted, 'utf8', function (err) {
    if (err) return console.log(err);
 });
});



回答2:


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 this 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


来源:https://stackoverflow.com/questions/53446570/replace-a-line-in-txt-file-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!