(JS)在迭代之后从CSV中删除线路



我希望您能够帮助我从脚本在该行上迭代的每一个脚本后从CSV文件中删除一行?以下代码可以通过CSV迭代并按线执行功能(这是通过将所有数据加载到数组中以提高速度的)来效法的,但是我想删除顶部条目 - 一个刚刚使用的 - 来自CSV。目的是让跑步者能够连续调用任务,即使它崩溃了:

fs = require('fs');
function readCsv(filename) {
    file = fs.open(filename, 'r');
    line = file.readLine();
        var next = function() {
            line = file.readLine();
            task(line, next)
        };
    task(line, next);
function task(data, callback) {
    // Thing to do with data
}

使用流类似的东西应该起作用。

const Transform = require('stream').Transform;
const util = require('util');
const Readable = require('stream').Readable;
const fs = require('fs');

class ProcessFirstLine extends Transform {
    constructor(args) {
        super(args);
        this._buff = '';
    }
    _transform(chunk, encoding, done) {
            // collect string into buffer
            this._buff += chunk.toString();
            // Create array of lines
            var arr = this._buff
                        .trim() // Remove empty lines at beginning and end of file
                        .split(/n/), // Split lines into an array
                len = arr.length; // Get array length

            if(len > 0) {
                // Loop through array and process each line
                for(let i = 0; i < len; i++) {
                    // Grab first element from array
                    let line = arr.shift();
                    // Process the line
                    this.doSomethingWithLine(line);
                }
                // Push our array as a String (technically should be empty)
                this.push(arr.join(/n/));
                // Empty the buffer
                this._buff = null;
            }
        done();
    }
    doSomethingWithLine(line) {
        console.log("doSomething:"+line);
    }
}
var input = fs.createReadStream('test.txt'); // read file
var output = fs.createWriteStream('test_.txt'); // write file
input
    .pipe(new ProcessFirstLine()) // pipe through line remover
    .pipe(output); // save to file

最新更新