2017-02-16 76 views
1

我希望你能幫我在csv文件中刪除一行,每一個腳本在該行上迭代之後?下面的代碼可以正常工作,通過遍歷CSV並在每行的基礎上執行一個函數(這是爲了提高速度將所有數據加載到一個數組中選擇的),但是我想刪除頂部條目 - 一個剛剛使用 - 從csv。目標是讓跑者能夠連續致電任務,即使它崩潰:(JS)迭代後從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 
} 

回答

0

像這樣使用流應該工作。

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