如何从txt文件中删除一行

我有以下要在node.js中操作的文本文件(“ test.txt”):

world

food

我想删除第一行,以使其food成为第一行。我怎样才能做到这一点?

回答:

var fs = require('fs')

fs.readFile(filename, 'utf8', function(err, data)

{

if (err)

{

// check and handle err

}

// data is the file contents as a single unified string

// .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)

// .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")

// .join() takes that array and re-concatenates it into a string

var linesExceptFirst = data.split('\n').slice(1).join('\n');

fs.writeFile(filename, linesExceptFirst);

});

以上是 如何从txt文件中删除一行 的全部内容, 来源链接: utcz.com/qa/419602.html

回到顶部