[英]How to create an array entry for each line of a text file using node.js
[英]How can I add text to the end of each line of a File in node.js?
我有一个名为Names.txt的文件; 在里面是一个人名列表,用一行分隔。 例如;
Joe
Alex
Patricia
Emma
如何在node.js中编辑文件,以便在每行中添加一个“:lastname”?
您将得到文件,分成几行,修改这些行,然后再次写回文件
fs.readFile('/path/to/Names.txt', function(err, result) {
if (err) // handle errors
var lines = result.split(/(\n|\r\n)/);
var new_content = lines.map(function(line) {
return line + ' lastname';
}).join("\r\n")
fs.writeFile('/path/to/Names.txt', new_content, 'utf8', function(err) {
if (err) // handle errors
console.log('The file has been saved!');
});
});
这就是关键。 当然,您可以保留名字和姓氏的映射,并插入适当的姓氏,或进行其他各种操作,但是您仍然必须经历相同的过程,获取,在换行符上分割,修改,连接在一起并保存。
基于先前的答案,您将希望通过将UTF8编码实现为文件路径之后的参数来添加UTF8编码,如下所示:
fs.readFile('/path/Names.txt', 'utf8', function(err, res) {
if (err) throw err;
var lines = res.split(/\n/);
var new_content = lines.map(function(line) {
return line + ' lastname';
}).join('\n');
fs.writeFile('/path/Names.txt', new_content, 'utf8', function(err) {
if (err) throw err;
console.log('The file has been saved!');
});
});
这应该可以解决您的缓冲区看起来像是从读取命令返回的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.