2014-01-10 97 views
6

目前我正在使用node-csv(http://www.adaltas.com/projects/node-csv/)進行csv文件解析。如何用node-csv解析器跳過文件的第一行?

有沒有辦法在開始解析數據之前跳過文件的前幾行?例如,某些csv報告在實際標題和數據啓動之前的前幾行中具有報告詳細信息。

LOG REPORT     <- data about the report 
DATE: 1.1.1900 
DATE,EVENT,MESSAGE   <- data headers 
1.1.1900,LOG,Hello World! <- actual data stars here 
+1

對此有何好運?我正在使用相同的庫,並且具有相同的問題。 – ac360

回答

4

你這裏有兩種選擇:

  1. 可以處理文件中的行由行。我之前在answer中發佈了代碼段。你可以使用

    var rl = readline.createInterface({ 
        input: instream, 
        output: outstream, 
        terminal: false 
    }); 
    
    rl.on('line', function(line) { 
        console.log(line); 
        //Do your stuff ... 
        //Then write to outstream 
        rl.write(line); 
    }); 
    
  2. 你可以給你的文件流一個偏移量來跳過這些字節。你可以看到它在documentation

    fs.createReadStream('sample.txt', {start: 90, end: 99}); 
    

    這是容易得多,如果你知道偏移是固定的。

+0

+1用於建議使用偏移量創建新流,並將所有內容都保存爲流,因此node.js-ish。 – booyaa

5

假設你正在使用V0.4或更高版本與新的重構(即CSV-產生,CSV,解析,流轉換和CSV-字符串化),可以使用內置的變換,跳過第一行,做一些額外的工作。

var fs = require('fs'), 
    csv = require('csv'); 

var skipHeader = true; // config option 

var read = fs.createReadStream('in.csv'), 
    write = fs.createWriteStream('out.jsonish'), 
    parse = csv.parse(), 
    rowCount = 0, // to keep track of where we are 
    transform = csv.transform(function(row,cb) { 
     var result; 
     if (skipHeader && rowCount === 0) { // if the option is turned on and this is the first line 
      result = null; // pass null to cb to skip 
     } else { 
      result = JSON.stringify(row)+'\n'; // otherwise apply the transform however you want 
     } 
     rowCount++; // next time we're not at the first line anymore 
     cb(null,result); // let node-csv know we're done transforming 
    }); 

read 
    .pipe(parse) 
    .pipe(transform) 
    .pipe(write).once('finish',function() { 
     // done 
    }); 

本質上講,我們跟蹤已經轉化的行數,如果我們在最前面的一個(和我們,其實希望通過skipHeader布爾忽略標題),然後傳遞null回調作爲第二個參數(第一個總是錯誤),否則傳遞轉換後的結果。

這也適用於同步解析,但需要更改,因爲在同步模式下沒有回調。而且,同樣的邏輯可以應用於較舊的v0.2庫,因爲它也具有內置的行轉換。

http://csv.adaltas.com/transform/#skipping-and-creating-records

這是很容易申請,並IMO具有相當低的足跡。通常情況下,您希望跟蹤出於狀態目的而處理的行,並且在將結果集發送到Writable之前,我幾乎總是轉換結果集,因此只需添加額外的邏輯來檢查跳過標頭就非常簡單。這裏額外的好處是,我們使用相同的模塊來應用跳過邏輯,因爲我們要解析/轉換 - 不需要額外的依賴關係。

相關問題