Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle an input prompt with node when executing a command via child_process?

For context, I'm on a Mac and I'm trying to script a 1Password CLI signin via their command-line tool. I'm trying to programmatically sign in using a command that looks like:

op signin <signinaddress> <emailaddress> <secretkey> --output=raw

and I've tried with/without the --output=raw argument, but every time I simply get an error that looks like

[LOG] 2019/06/04 00:57:45 (ERROR) operation not supported on socket

child process exited with code 1

My initial hunch was that it had something to do with the command executions prompt displaying this special key character in the following image:

op signin prompt img

The relevant code is written in TypeScript and looks like this:

import { spawn } from 'child_process'

// ends up being `op signin <signinaddress> <emailaddress> <secretkey>`
const op = spawn(opExecutable, args);
let result: string | null = null

op.on('message', (message, sendHandle) => {
  console.log('message', message, sendHandle)
});
op.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
  if (data && typeof data.toString === 'function') {
    result = data.toString()
  }
});

op.on('close', (code, ...args) => {
  console.log(`child process exited with code ${code}`, args);
});

Eventually, I'd like to run on all platforms and be able pass in stdin for the master password required to sign in, but I'm trying to figure out why my node app is crashing first :)

like image 653
edhedges Avatar asked Jan 24 '26 12:01

edhedges


1 Answers

Apparently I was pretty close to a solution by using spawn, but I needed to specify configuration for stdio. Here's an example snippet of how I used spawn that worked for me:

const proc = spawn(
  cmd, // the command you want to run, in my case `op`
  args, // arguments you want to use with the above cmd `signin`, etc.
  {
    stdio: [
      'inherit', // stdin: changed from the default `pipe`
      'pipe', // stdout
      'inherit' // stderr: changed from the default `pipe`
    ]
  });
like image 84
edhedges Avatar answered Jan 26 '26 04:01

edhedges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!