Search code examples
node.jspermissionsspawn

Node JS, ask permission when executing Spawn command


I have some script written in nodejs which uses spawn to execute some cmd command:

let cmd = spawn("command name", ["my", "arguments"], {cwd: 'pth where it will be executed'});

cmd.stdOut.on('data', (data) => {/*Handle some output*/})

Sometimes code that I need to execute will ask permission (some users may have password).

How to ask permission then continue executing this command? I know that it will be simple to just launch code as admin or superuser, but not all users will do that.


Solution

  • When you are spawning the process you could pass {stdio: 'inherit'}. Then child process will use parent's stdin, stdout and stderr which means if child process will need sudo rights you'll see the message like 'Password:' coming from the child and you'll be able to type it in.

    I just tested it like this:

    const {spawn} = require('child_process');
    
    let cmd = spawn('sudo', ['ls'], {stdio: 'inherit'});
    //Also works like this
    let cmd = spawn('./requires-sudo.sh', {stdio: 'inherit'});

    Notice that you don't need to listen to 'data' event anymore as stdout is same for parent and child, so you'll see the output.