unhackit
unhackit

Reputation: 561

How to run two child processes in succession in node JS

I have two processes, one to generate a json file from an audio and the other one to normalize the json file, they are both in a function.

Each time i run the function and the first one runs, the second one refuses to run and when the second one runs, the first one refuses to run.

I want to be able to run the second one after the first one.

exec(command, (error, stdout, stderr) => {
    if (error) {
      console.log("Normalize error", error);
      return;
    }
    if(stderr){
      console.log(`stderr: ${stderr}`);
      return
    } 
    console.log(`stdout: ${stdout}`);
  });

The code above is the one that generates the audio file

 exec(`python3 py/scale-json.py json/${song.filename}/.json`, (error, stdout, stderr) => {
        console.log("I AM EXECUTING", song.filename)
        if (error) {
        console.log("Python error", error);
        }
        console.log(`stdout-python: ${stderr}`);
    })

While the code above normalizes it.

How do i run them one after the other ?

Upvotes: 0

Views: 880

Answers (2)

jfriend00
jfriend00

Reputation: 708046

I'd promisify the exec() function and then use promise-based logic to sequence them:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function run() {
    const { stdout: stdout1, stderr: stderr1 } = await exec(command);

    // some logic based on stdout1 or stderr1
    
    const { stdout: stdout2, stderr: stderr2 } = await exec(`python3 py/scale-json.py json/${song.filename}/.json`);

    // process final results here
    return something;
}

// Call it like this:
run().then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

You can read about how util.promisify() works with child_process.exec() here in the doc.

Upvotes: 2

Iago Calazans
Iago Calazans

Reputation: 328

have u tried to use the Normalizer as a callback part?

 exec(`python3 py/scale-json.py json/${song.filename}/.json`, (error, stdout, stderr) => {
        console.log("I AM EXECUTING", song.filename)
        if (error) {
            throw new Error (error);
        }
        console.log(`stdout-python: ${stderr}`);

        // It goes here!
        exec(command, (error, stdout, stderr) => {
            if (error) {
                console.log("Normalize error", error);
                return;
            }
            if(stderr){
                console.log(`stderr: ${stderr}`);
                reject("error");
                return;
            } 
            resolve("complete")
            console.log(`stdout: ${stdout}`);
        });
    })

Upvotes: 0

Related Questions