Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js pass text as stdin of `spawnSync`

I'd think this would be simple, but the following does not work as expected.

I want to pipe data to a process, say (just an arbitrary command for illustration) wc, from Node.

The docs and other SO questions seem to indicate that passing a Stream should work:

const {spawnSync} = require('child_process')
const {Readable} = require('stream')

const textStream = new Readable()
textStream.push("one two three")
textStream.push(null)

const stdio = [textStream, process.stdout, process.stderr]
spawnSync('wc', ["-c"], { stdio })

Unfortunately this throws an error:

The value "Readable { ... } is invalid for option "stdio"

The relevant bit of code from internal/child_process.js does not immediately reveal what the anticipated valid options are.

like image 358
Brian M. Hunt Avatar asked Jul 03 '17 18:07

Brian M. Hunt


1 Answers

To present particular data as stdin data for the child process, you can use the input option:

spawnSync('wc', ['-c'], { input : 'one two three' })
like image 163
robertklep Avatar answered Oct 24 '22 15:10

robertklep