I'm writing an application that downloads YouTube videos with the extension node-ytdl. I'd like to send the client a progress indicator on the download, so I'm trying to get chunk information to compute it. My code looks kind of like this.

        var writing = fs.createWriteStream('video.mp4');
        var stream = ytdl('https://www.youtube.com/watch?v=jofNR_WkoCE', { filter: function(format) { return format.container === 'mp4'; }, quality: "lowest" });
        stream.pipe(writing);

        var completed_len = 0;
        var total_len = 0;

        writing.on('data', function(chunk) {
            console.log('received data!');
            completed_len += chunk.length;
        });

        writing.on('close', function ()
        {
            console.log('close');
            res.send('completed!');
        });

Weirdly enough, even though 'close' fires whenever the download is done, I'm not getting any logs from the 'data' event. The video is written correctly. I'm kind of new to Node.js streams. Have I done something wrong?

有帮助吗?

解决方案

You've just bound to the wrong stream. 'data' events will occur on readable streams, like the stream created by ytdl.

stream.on('data', function (chunk) {
    // ...
});

And 'close' events will occur on both streams if you're using Node 0.8 or older. While 0.10 changed the event for writable streams to 'finish'.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top