简体   繁体   中英

Getting the progress output of a child spawned process from nodejs

I'm playing in spawning npm install -g create-react-app from a js script. I want to get in real time the part of the output, where you can see the progress of the package's installation process. I mean this:

在此处输入图片说明

But when I execute the script, the output is this when installing:

+ create-react-app@2.1.8
added 63 packages from 20 contributors in 4.885s

and this when updating:

+ create-react-app@2.1.8
updated 1 package in 1.971s

The code I'm using:

const run = (cmd, args) => {
    return new Promise((resolve, reject) => {
        const spawn = require('child_process').spawn;
        const command = spawn(cmd, args);
        let result = '';
        command.stdout.on('data', data => {
            result += data.toString()
        });
        command.on('close', _ => {
            resolve(result)
        });
        command.on('error', err => {
            reject(err)
        });
    })
}

run(npmExecutable, ["install", "-g", "create-react-app"]).then(result => {
    console.log(result);
});

So, it's possible to get the desire real time output where you can see the progress bar?

EDIT: Well, according to Mark's answer I can see now the progess bar , but how I can output this result (progress bar) in real time to stdout , I mean to a variable?

This is the new code:

const run = (cmd, args) => {
    return new Promise((resolve, reject) => {
        const spawn = require("child_process").spawn;
        const command = spawn(cmd, args, {
            stdio: "inherit"
        });
        command.on("close", _ => {
            resolve();
        });
        command.on("error", err => {
            reject(err);
        });
    });
};

EDIT ABOUT DUPLICATE: My question is different from the other one, because now I'm trying to resolve another issue using the answer (comments) I received from the other question !

NPM is avoiding the animations and progress bar when output is being directed through a pipe. Assuming this is the top level parent process, you can specify an option to direct all STDIO options to the host.

const command = spawn(cmd, args, {stdio: 'inherit'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM