繁体   English   中英

如何使用节点 js 更改文件中的特定行?

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

我想使用带有 fs 模块的节点 js 更改文本文件中的特定行。

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

旧文件:

Line 1
Line 2
Line 3

新文件:

Line 1
something new
Line 3

感谢您的回复!

尝试使用这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM