我想在node.js中操作以下文本文件(" test.txt"):
world
food
我想删除第一行,以便food
成为第一行。我怎么能这样做?
答案 0 :(得分:16)
var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
if (err)
{
// check and handle err
}
var linesExceptFirst = data.split('\n').slice(1).join('\n');
fs.writeFile(filename, linesExceptFirst);
});
答案 1 :(得分:0)
我刚遇到需要能够排除文件中多行的需求。这是我使用简单的节点函数完成的方法。
const fs = require('fs');
const removeLines = (data, lines=[]) => {
return data
.split('\n')
.filter((val, idx) => lines.indexOf(idx) === -1)
.join('\n');
}
fs.readFile(fileName, 'utf8', (err, data) => {
if (err) throw err;
// remove the first line and the 5th and 6th lines in the file
fs.writeFile(fileName, removeLines(data, [0, 4, 5]), 'utf8);
})
答案 2 :(得分:0)
使用替换
const fs = require('fs');
function readWriteSync() {
var data = fs.readFileSync(filepath, 'utf-8');
// replace 'world' together with the new line character with empty
var newValue = data.replace(/world\n/, '');
fs.writeFileSync(filepath, newValue, 'utf-8');
}