2017-04-10 102 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