gpt4 book ai didi

javascript - (JS) 迭代后从 csv 中删除行

转载 作者:行者123 更新时间:2023-11-28 04:59:14 27 4
gpt4 key购买 nike

我希望您能够帮助我在每次脚本迭代该行后从 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
}

最佳答案

像这样使用 Stream 应该可以工作。

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

关于javascript - (JS) 迭代后从 csv 中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com