Node.js如何删除文件中的第一行

我正在做简单的Node.js应用程序,我需要删除文件中的第一行。 请问是怎么做的? 我认为这将是可能的fs.write,但如何?

这里是从文件中删除第一行的stream式版本。
因为它使用stream,意味着你不需要在内存中加载整个文件,所以它更加高效和快速,而且可以在非常大的文件上工作而不需要在硬件上填充内存。

var Transform = require('stream').Transform; var util = require('util'); // Transform sctreamer to remove first line function RemoveFirstLine(args) { if (! (this instanceof RemoveFirstLine)) { return new RemoveFirstLine(args); } Transform.call(this, args); this._buff = ''; this._removed = false; } util.inherits(RemoveFirstLine, Transform); RemoveFirstLine.prototype._transform = function(chunk, encoding, done) { if (this._removed) { // if already removed this.push(chunk); // just push through buffer } else { // collect string into buffer this._buff += chunk.toString(); // check if string has newline symbol if (this._buff.indexOf('\n') !== -1) { // push to stream skipping first line this.push(this._buff.slice(this._buff.indexOf('\n') + 2)); // clear string buffer this._buff = null; // mark as removed this._removed = true; } } done(); }; 

像这样使用它:

 var fs = require('fs'); var input = fs.createReadStream('test.txt'); // read file var output = fs.createWriteStream('test_.txt'); // write file input // take input .pipe(RemoveFirstLine()) // pipe through line remover .pipe(output); // save to file 

另一种方式,这是不推荐的。
如果你的文件不是很大,你不介意把它们加载到内存中,加载文件,删除行,保存文件,但速度较慢,并且在大文件上不能正常工作。

 var fs = require('fs'); var filePath = './test.txt'; // path to file fs.readFile(filePath, function(err, data) { // read file to memory if (!err) { data = data.toString(); // stringify buffer var position = data.toString().indexOf('\n'); // find position of new line element if (position != -1) { // if new line element found data = data.substr(position + 1); // subtract string based on first line length fs.writeFile(filePath, data, function(err) { // write file if (err) { // if error, report console.log (err); } }); } else { console.log('no lines found'); } } else { console.log(err); } }); 

受另一个答案启发,这是一个修订stream版本:

 const fs = require('fs'); const readline = require('readline'); const removeFirstLine = function(srcPath, destPath, done) { var rl = readline.createInterface({ input: fs.createReadStream(srcPath) }); var output = fs.createWriteStream(destPath); var firstRemoved = false; rl.on('line', (line) => { if(!firstRemoved) { firstRemoved = true; return; } output.write(line + '\n'); }).on('close', () => { return done(); }) } 

并且可以通过将“firstRemoved”更改为计数器来轻松修改以删除一定数量的行:

 var linesRemoved = 0; ... if(linesRemoved < LINES_TO_BE_REMOVED) { linesRemoved++; return; } ...