如何从txt文件中删除一行

时间:2016-08-09 05:52:28

标签: node.js

我想在node.js中操作以下文本文件(" test.txt"):

world
food

我想删除第一行,以便food成为第一行。我怎么能这样做?

3 个答案:

答案 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');
}
相关问题