我想使用带有 fs 模块的节点 js 更改文本文件中的特定行。
有没有比将文件加载到数组更优雅的方法?
旧文件:
Line 1
Line 2
Line 3
Run Code Online (Sandbox Code Playgroud)
新文件:
Line 1
something new
Line 3
Run Code Online (Sandbox Code Playgroud)
感谢您的回复!
小智 7
尝试使用这个:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,请访问 https://www.npmjs.com/package/replace-in-file。
| 归档时间: |
|
| 查看次数: |
3962 次 |
| 最近记录: |