【问题标题】:How can I change a specific line in a file with node js?如何使用节点 js 更改文件中的特定行?
【发布时间】:2015-08-23 00:57:26
【问题描述】:

我想使用 node js 和 fs 模块更改文本文件中的特定行。

有没有比将文件加载到数组中更优雅的方式?

旧文件:

Line 1
Line 2
Line 3

新文件:

Line 1
something new
Line 3

感谢您的回复!

【问题讨论】:

标签: node.js file fs


【解决方案1】:

试试这个:

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);
 });
});

如果这不起作用,请访问https://www.npmjs.com/package/replace-in-file

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多