Search code examples
node.jsforkspawn

node.js send commands to non js child process shell


I'm using inkscape's CLI from node.js, this works already fine, I'v heard that this would be more performant if I was using the --shell parameter of inkscape so the idea is to leave a process open and just send commands whenever I want to execute them to the child.

I tried using spawn (this command does open an svg file):

 const child = spawn(`${inkscapePath} "${projectPathSvg}"`, { shell: true })

If I don't put shell:true it doesn't look like is doing anything, and with shell:true is going to open an inkscape tab but without window, but anyways this is not doing a whole lot, when I try to use child.send(command) I get an error: enter image description here

Any ideas or tutorials on how to approach this? Thanks!


Solution

  • inkscape --shell is a completely different thing than what shell means in spawn. The latter just means that you are running the process in a new shell, like bash. --shell for inkscape means that you will be put in a REPL shell where you can send commands to a running inkscape process.

    Furthermore, the child.send you are referring to only works when an IPC channel was established with the child, which doesn't happen in spawn, only in fork which only works when the child is a nodejs process again.

    What you really seem to be wanting to do then is to communicate with the open shell process of inkscape --shell, sending commands programmatically from nodejs. For this you'll need to use the stdin and stdout pipes setup by spawn.

    Something like this might work:

    const inkscape = spawn('inkscape', ['--shell']);
    inkscape.stdin.write('my-inkscape-command');
    

    Not sure whether inkscape has an API that would be better suited than this, but the approach seems worth exploring.