节点streamread()函数为什么会返回null的原因?

我正在构build一个节点应用程序,它从文件系统读取CSV文件,分析文件,然后使用csv-parse模块parsing文件。 这些步骤中的每一步都是以stream的forms传送到下一个。

我遇到的麻烦是,对于一些文件,parsing步骤可以读取stream,但对于其他人来说, read()方法在readable事件上返回null ,我不知道为什么。

在下面的代码中,具体来说,我有时会看到数据通过调用parsing器stream上的read() ,而其他时间将返回null 。 成功的CSV文件总是成功的,失败的CSV文件总是失败。 我试图确定文件之间的一些区别,但除了在第一行中使用不同的字段名称,以及在正文中略有不同的数据之外,我看不到源文件之间的任何显着差异。

什么是节点stream的read()函数在readable事件之后可能返回null一些原因?

示例代码:

 var parse = require('csv-parse'); var fs = require('fs'); var stream = require('stream'); var byteCounter = new stream.Transform({objectMode : true}); byteCounter.setEncoding('utf8'); var totalBytes = 0; // count the bytes we have read byteCounter._transform = function (chunk, encoding, done) { var data = chunk.toString(); if (this._lastLineData) { data = this._lastLineData + data ; } var lines = data.split('\n'); // this is because each chunk will probably not end precisely at the end of a line: this._lastLineData = lines.splice(lines.length-1,1)[0]; lines.forEach(function(line) { totalBytes += line.length + 1 // we add an extra byte for the end-of-line this.push(line); }, this); done(); }; byteCounter._flush = function (done) { if (this._lastLineData) { this.push(this._lastLineData); } this._lastLineData = null; done(); }; // csv parser var parser = parse({ delimiter: ",", comment: "#", skip_empty_lines: true, auto_parse: true, columns: true }); parser.on('readable', function(){ var row; while( null !== (row = parser.read()) ) { // do stuff } }); // start by reading a file, piping to byteCounter, then pipe to parser. var myPath = "/path/to/file.csv"; var options = { encoding : "utf-8" }; fs.createReadStream(myPath, options).pipe(byteCounter).pipe(parser);