Node.js 如何使用node js更改文件中的特定行?
我想使用节点js和fs模块更改文本文件中的特定行 有没有比将文件加载到数组中更优雅的方法 旧文件:Node.js 如何使用node js更改文件中的特定行?,node.js,file,fs,Node.js,File,Fs,我想使用节点js和fs模块更改文本文件中的特定行 有没有比将文件加载到数组中更优雅的方法 旧文件: 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.re
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);
});
});
如果这不起作用,请访问。尝试另一个问题中给出的可能重复的解决方案也很有帮助