对如何在node.js中实现异步回调感到困惑

时间:2016-01-02 05:07:07

标签: javascript node.js asynchronous

ytdl(url, { filter: function(format) { return format.container === 'mp4'; } })
    .pipe(fs.createWriteStream('./songs/Battle-Scars.mp4'));

我是node.js的新手,我正在尝试实现一个youtube-mp3转换器,而且我不知道如何在上面的代码运行完成后才运行以下代码。

var proc = new ffmpeg({ source: './songs/Battle-Scars.mp4'})
    .withAudioCodec('libmp3lame')
    .toFormat('mp3')
    .saveToFile('./songs/Battle-Scars.mp3', function(stdout, stderr) {
        console.log('file has been converted succesfully');
    });

我非常感谢所有的帮助和感谢。

1 个答案:

答案 0 :(得分:2)

由于您正在使用流,因此您可能需要查看在写入流写入磁盘后可以触发的finish event

尝试类似:

var writeStream = fs.createWriteStream('./songs/Battle-Scars.mp4');

// Set up event listener
writeStream.on('finish', function () {
  var proc = new ffmpeg({ source: './songs/Battle-Scars.mp4'})
    .withAudioCodec('libmp3lame')
    .toFormat('mp3')
    .saveToFile('./songs/Battle-Scars.mp3', function(stdout, stderr) {
      console.log('file has been converted succesfully');
    });
});

ytdl(url, { filter: function(format) { return format.container === 'mp4'; } })
.pipe(writeStream);