Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用node js更改文件中的特定行?_Node.js_File_Fs - Fatal编程技术网

Node.js 如何使用node js更改文件中的特定行?

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

我想使用节点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.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);
 });
});

如果这不起作用,请访问。

尝试另一个问题中给出的可能重复的解决方案也很有帮助