Node Js child_process > exec: How to return stdout continuously of child script in paent script?

Viewed 155

I have array of script which contains the command of another script.

[
  'node controllers/script_one/import.js main init',
  'node controllers/script_two/import.js main init'
]

I have pass the above array to below function to run the commands one by one.

async function exec_commands(commands,index = 0)
{
    let command = commands.shift();
    exec(command, (error, stdout, stderr) => {
        
        if (error) 
        {
            log.error("*****************************************************");
            log.error("error Occured in command:");
            log.error(error);
            log.error("*****************************************************");
        }
        if(stdout)
        {
            log.info("*****************************************************");
            log.info("shell Logs:");
            log.info(stdout);
            log.info("*****************************************************");
        }

        if(stderr)
        {
            log.info("*****************************************************");
            log.info("shell:");
            log.info(stderr);
            log.info("*****************************************************");
        }

        index++;

        if(commands.length) 
        {
            log.info("Executing Next Command From Array, Loop Index:"+index);
            exec_commands(commands,index)
        }
        else
        {
            process.exit(0);
        }

    });

}

Now this function is in another script main_script.js.

after running the command node main_script.js, both command runs one by one, but 2nd command is taking too much time because of its internal processes, it gives below error on terminal.

packet_write_wait: Connection to <IP ADDRESS> port 22: Broken pipe

because child process is not return anything until it complete its processes.

So, How can we print the logs continuously in exec_commands function while running the child commands?

0 Answers
Related