使用Node.js,如何在subprocess上执行多个命令并在每个命令之后获得响应?

我试图使用Node.js通过Inkscape获取有关多个SVG文件的信息。

我可以运行像Inkscape file.svg --select=id -W & Inkscape file2.svg --select=id -W (获取两个文件的宽度),但它使用两个Inkscape实例,这是慢。

使用Inkscape的--shell选项,您可以非常快地运行多个命令,因为Inkscape只初始化一次。 http://tavmjong.free.fr/INKSCAPE/MANUAL/html/CommandLine.html

然而,我不知道如何使用Inkscape shell与Node.js,因为所有的child_processtypes似乎都希望每个命令后的响应和退出,否则它挂起,直到超时或程序closures。

我喜欢下面的某种function。

 var Inkscape = require('hypothetical_module').execSync('Inkscape --shell'); var file1width = Inkscape.execSync('file.svg -W'); var file2width = Inkscape.execSync('file2.svg -W'); if(file1width > 200){ Inkscape.execSync('file.svg --export-pdf=file.pdf'); } if(file2width > 200){ Inkscape.execSync('file2.svg --export-pdf=file2.pdf'); } Inkscape.exec('quit'); 

下面是一个从cmd运行Inkscape的示例,其中包含名为“acid.svg”的testing文件

 C:\Program Files (x86)\Inkscape>Inkscape --shell Inkscape 0.91 r13725 interactive shell mode. Type 'quit' to quit. >acid.svg -W 106>acid.svg -H 93.35223>quit 

你将不得不停止使用同步命令。 这是一个玩具的例子:

我打电话给这个程序, repl.sh

 #!/bin/sh while :; do printf "> " read -r cmd case "$cmd" in quit) echo bye; exit ;; *) echo "you wrote: $cmd" ;; esac done 

而且,node.js代码:

 #!/usr/local/bin/node var spawn = require('child_process').spawn, prog = './repl.sh', cmdno = 0, cmds = ['foo -bar -baz', 'one -2 -3', 'quit']; var repl = spawn(prog, ['--prog', '--options']); repl.stdout.on('data', function (data) { console.log('repl output: ' + data); if (cmdno < cmds.length) { console.log('sending: ' + cmds[cmdno]); repl.stdin.write(cmds[cmdno] + "\n"); cmdno++ } }); repl.on('close', function (code) { console.log('repl is closed: ' + code); }); repl.on('error', function (code) { console.log('repl error: ' + code); }); 

这输出:

 $ node repl.driver.js repl output: > sending: foo -bar -baz repl output: you wrote: foo -bar -baz > sending: one -2 -3 repl output: you wrote: one -2 -3 > sending: quit repl output: bye repl is closed: 0