NodeJS:使用可读事件和排水事件

时间:2015-01-19 10:04:31

标签: javascript node.js express stream node.js-stream

我正在尝试使用节点的可读流来读取大文件(~800 MB)。 我已经订阅了'可读'事件,在获取我正在写入响应的数据时,然后等待drain事件再次读取数据。但排水事件仅被触发3-4次。如果有任何问题,请告诉我。

// Assume res to be any writable stream.

var readStream = fs.createReadStream('C:/movie.mp4');

readStream
    .on('error', function (err) {
    })
    .on('readable', function () {
        console.log('READABLE event fired');
        writeStreamData(readStream, res);
    })
    .on('end', function () {
        console.log('END event fired');
        res.end();
    });

function writeStreamData(readStream, res) {
    var chunk, isFlushed;
    console.log('in writeStreamData');
    if (null !== (chunk = readStream.read(1024 * 1000))) {
        console.log('writing data');
        isFlushed = res.write(chunk);
        if (!isFlushed) {
            console.log('waiting for drain event');
            res.once('drain', function () {
                console.log('*** DRAIN event triggered');
                writeStreamData(readStream, res);
            });
        } else {
            writeStreamData(readStream, res);
        }
    }
}

0 个答案:

没有答案