Node.js 读取 TXT 文件并插入新行字符串
可以使用 Node.js 中的 fs 模块读取 txt 文件,然后使用字符串拼接的方式插入一行字符串,最后再写回到 txt 文件中。
例如:
const fs = require('fs');
// 读取 txt 文件
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
// 在第二行插入字符串
const lines = data.split('
');
lines.splice(1, 0, 'new line
');
const newText = lines.join('
');
// 写回到 txt 文件中
fs.writeFile('test.txt', newText, (err) => {
if (err) {
console.error(err);
return;
}
console.log('文件已更新');
});
});
以上代码中,我们首先使用 fs.readFile 方法读取 txt 文件,然后使用 split 方法把文件内容按行分割成数组 lines,再使用 splice 方法在第二行插入字符串 'new line\n',最后使用 join 方法把数组合并成字符串 newText。
接着,我们使用 fs.writeFile 方法把 newText 写回到 txt 文件中,如果出现错误,则打印错误信息,否则打印 '文件已更新'。
原文地址: https://www.cveoy.top/t/topic/ndlr 著作权归作者所有。请勿转载和采集!