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

标签 node.js file line

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

最佳答案

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

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);
    }
});

关于Node.js如何删除文件中的第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363206/

相关文章:

c# - 在 C# 中监视文件更改

javascript - nodejs express:将参数存储在变量中

node.js - 为什么在使用 Passport/Node Express 的 OAuth2Strategy 进行身份验证时出现 TokenError

c# - 如何读取带有自定义扩展名的文本框的文件

vb.net - 为什么 '?' 在打印中文文本时显示为输出

python - 如何在python中将文件从文件夹A move 到文件夹B?

java - 删除文本文件中的多余行

algorithm - 将线段限制为矩形的边界

node.js - 通过套接字向 Bitfinex 发出请求的限制是多少?

javascript - 关于node.js中fs的问题