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

use*_*602 12 file line node.js

我正在制作简单的Node.js应用程序,我需要删除文件中的第一行.请问有什么办法吗?我认为用fs.write会有可能,但是怎么样?

mok*_*oka 15

这是从文件中删除第一行的流式版本.
因为它使用流,意味着您不需要在内存中加载整个文件,因此它更加高效和快速,并且可以处理非常大的文件而无需在硬件上填充内存.

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();
};
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

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
Run Code Online (Sandbox Code Playgroud)

另一种方式,不推荐.
如果您的文件不大,并且您不介意将它们加载到内存中,请加载文件,删除行,保存文件,但它速度较慢,并且在大文件上无法正常工作.

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 我根据这个答案创建了一个简单的库。它允许您删除 X 行。您所做的就是将金额传递给函数,然后就可以了。它被称为 **striplines**,位于 [npmjs.org](https://www.npmjs.com/package/striplines) (2认同)

ahg*_*ood 5

这是另一种方式:

const fs = require('fs');
const filePath = './table.csv';

let csvContent = fs.readFileSync(filePath).toString().split('\n'); // read file and convert to array by line break
csvContent.shift(); // remove the the first element from array
csvContent = csvContent.join('\n'); // convert array back to string

fs.writeFileSync(filePath, csvContent);
Run Code Online (Sandbox Code Playgroud)

  • @ahe_borriglione 其他解决方案是“丑陋的”,因为它们避免将整个文件加载到内存中。尽管此解决方案非常简单,但许多只想删除文件的“第一行”的人都会这样做,因为他们正在处理不想加载到内存中的大文件。它还使用同步文件操作(而不是异步),并将整个文件解析为一个数组,只是为了从中删除一个元素。在许多简单的脚本中,这是一个不错的解决方案。但对于许多寻求此问题答案的人来说,这不一定是一个好的解决方案。 (4认同)
  • 第一个不难看的解决方案。谢谢 (3认同)