beekeeper
beekeeper

Reputation: 91

Confused on how to implement asynchronous callback in node.js

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

I am new to node.js and am trying to implement a youtube-mp3 converter, and I don't know how to make the following code run ONLY after the code above finishes running.

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');
    });

I appreciate all the help and thanks in advance.

Upvotes: 2

Views: 68

Answers (1)

thgaskell
thgaskell

Reputation: 13226

Since you are using streams, you might want to take a look at the finish event which you can trigger once your write stream has completed writing to disk.

Try something like:

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);

Upvotes: 2

Related Questions