Search code examples
javascriptnode.jsaudiogoogle-speech-api

how to prevent Async in NodeJS - wait for task a to complete before starting task b


I am in need to wait for task A to complete before executing task B code.

task A is to convert audio file and

task B uses the converted audio for further process.

because task A store new audio file to particular directory and task B is trying to access the file which does not exist my code breaks.

How do I make sure task B code executes once the new audio file is saved to a directory?

code

var track = fileURL;//your path to source file

  ffmpeg(track)
  .toFormat('flac')
  .on('error', function (err) {
      console.log('An error occurred: ' + err.message);
  })
  .on('progress', function (progress) {
      // console.log(JSON.stringify(progress));
      console.log('Processing: ' + progress.targetSize + ' KB converted');
  })
  .on('end', function () {
      console.log('Processing finished !');
  })
  .save(path.join(__dirname, '/public/downloads/Test.flac'));//path where you want to save your file

The above part of the code takes file from uploads folder converts it to new file format and saves it to the downloads directory.

You can see below I am trying to access the file (Test.flac) in downloads folder. There is lot more code but I need to execute this block of code only after completion of above task.

  const Speech = require('@google-cloud/speech');
  const projectId = 'uliq-68823';
  // Instantiates a client
  const speechClient = Speech({
   projectId: projectId
  });

  // The name of the audio file to transcribe

  const fileName2 = path.join(__dirname, '/public/downloads/' + 'Test.flac');

  // Reads a local audio file and converts it to base64
  const file2 = fs.readFileSync(fileName2);
  const audioBytes = file2.toString('base64');

Solution

  • The fluent-ffmpeg library uses streams to process your files. Therefore if you want to execute code after the stream is done, call your code in the callback called on the 'end' event of the stream.

    Example:

    var track = fileURL;//your path to source file
    
    ffmpeg(track)
    .toFormat('flac')
    .on('error', function (err) {
          console.log('An error occurred: ' + err.message);
    })
    .on('progress', function (progress) {
          // console.log(JSON.stringify(progress));
          console.log('Processing: ' + progress.targetSize + ' KB converted');
    })
    .on('end', function () {
          console.log('Processing finished !');
          // USE THE FILE HERE
          // <----------------
    })
    .save(path.join(__dirname, '/public/downloads/Test.flac'));