How do you pipe a long string to /dev/stdin via child_process.spawn() in Node.js?

后端 未结 4 1465
失恋的感觉
失恋的感觉 2021-02-07 07:39

I\'m trying to execute Inkscape by passing data via stdin. Inkscape only supports this via /dev/stdin. Basically, I\'m trying to do something like this

4条回答
  •  广开言路
    2021-02-07 08:23

    The problem comes from the fact that file descriptors in node are sockets and that linux (and probably most Unices) won't let you open /dev/stdin if it's a socket.

    I found this explanation by bnoordhuis on https://github.com/nodejs/node-v0.x-archive/issues/3530#issuecomment-6561239

    The given solution is close to @nmrugg's answer :

    var run = spawn("sh", ["-c", "cat | your_command_using_dev_stdin"]);
    

    After further work, you can now use the https://www.npmjs.com/package/posix-pipe module to make sure that the process sees a stdin that is not a socket.

    look at the 'should pass data to child process' test in this module which boils down to

    var p = pipe()
    var proc = spawn('your_command_using_dev_stdin', [ .. '/dev/stdin' .. ],
        { stdio: [ p[0], 'pipe', 'pipe' ] })
    p[0].destroy() // important to avoid reading race condition between parent/child
    proc.stdout.pipe(destination)
    source.pipe(p[1])
    

提交回复
热议问题