2016-12-06 69 views
1

我的用例是這樣的:我正在閱讀Node中的CSV文件,並只獲取標題。我不想將讀取流的結果寫入文件,而是一旦讀取文件就將頭推送到數組,所以我可以接受該數組並在稍後進行一些操作。或者,更好的方法是,在流中讀取數據流並進行轉換,然後將數據發送到數組。文件是一個人爲的價值。我被困在這一點上,在數據文件的電流輸出是一個空數組:管道NodeJS流到陣列

const fs = require('fs'); 
const parse = require('csv-parse'); 
const file = "my file path"; 
let dataFile = []; 

rs = fs.createReadStream(file); 
parser = parse({columns: true}, function(err, data){ 
    return getHeaders(data) 
}) 

function getHeaders(file){ 
    return file.map(function(header){ 
     return dataFile.push(Object.keys(header)) 
    }) 
} 

我需要做什麼才能得到我想要的結果呢?作爲最終結果,我期待在數組中找到標題。

回答

2

好,所以在你的代碼中的一些混亂的事情,和一個錯誤:你實際上並沒有打電話給你的代碼:)

首先,一個解決方案,加入這一行,分析器之後:

rs.pipe(parser).on('end', function(){ 
    console.log(dataFile); 
}); 

而magic,dataFile不是空的。 您從磁盤流式傳輸文件,將它傳遞給解析器,然後在最後調用回調函數。

對於混亂的部分:

parser = parse({columns: true}, function(err, data){ 
    // You don't need to return anything from the callback, you give the impression that parser will be the result of getHeaders, it's not, it's a stream. 
    return getHeaders(data) 
}) 

function getHeaders(file){ 
    // change map to each, with no return, map returns an array of the return of the callback, you return an array with the result of each push (wich is the index of the new object). 
    return file.map(function(header){ 
     return dataFile.push(Object.keys(header)) 
    }) 
} 

而且finaly: 請結束與;或沒有行選擇,而不是混合;)

你應該結束例如:

const fs = require('fs'); 
const parse = require('csv-parse'); 
const file = "./test.csv"; 
var dataFile = []; 

rs = fs.createReadStream(file); 
parser = parse({columns: true}, function(err, data){ 
    getHeaders(data); 
}); 

rs.pipe(parser).on('end', function(){ 
    console.log(dataFile); 
}); 

function getHeaders(file){ 
     file.each(function(header){ 
      dataFile.push(Object.keys(header)); 
     }); 
} 
+0

好,可靠的答案! –