2017-04-10 100 views
3

是否有可能停止活動並強制結束活動?Javascript停止活動

string rows // Correctly formatted csv string. 

csv 
    .fromString(rows, { headers: false }) 
    .on('data', (data) => { 
    if (condition) { 
     // force to end. 
    } 
    } 
    .on('end',() => cb(units)); 

因此,我期待早日脫離csv文件。

+0

您使用的是什麼csv庫? – jrook

+0

可能是https://github.com/Keyang/node-csvtojson –

+0

如果csv庫沒有處理您需要的驗證,那麼您可以[逐行讀取文件](http://stackoverflow.com/questions/ 42232026/search-text-file-with-readline-node-js/42301177#42301177)並按照您認爲合適的方式處理它。我認爲這同樣適用於用戶提供的字符串。 – jrook

回答

2

看來你正在使用node-csvtojson

我想你可以停止發射數據事件是這樣的:

const converter = csv.fromString(rows, { headers: false }) 
converter.on('data', (data) => { 
    if (condition) { 
    converter.removeAllListeners('data');// where 'data' is the name of the event. If called without any arguments, all listeners added to csv converter will be removed 
    } 
} 

來源:this thread on Github

+0

你試過了嗎?我試過上面的解決方案,它不工作。另外上面的off方法在文檔中沒有提到 –

+0

其實我沒有測試,我只是讀了這個[線程](https://github.com/Keyang/node-csvtojson/issues/127)。但是我讀得太快了,你顯然必須使用'removeAllListeners'而不是'off'。 –

+0

很酷。這很奏效。乾杯隊友:) –

1

這是怎麼回事?

const task = csv.fromString(rows, { headers: false }) 
task.on('data', (data) => { 
    if (condition) { 
    task.on('end',() => cb(units)); 
    } 
} 
+2

我不會那樣做。在調用'data'之前,'end'回調應該存在。 – Sebas