【问题标题】:Using Node.js, how can I execute mutiple commands on a child process and get the response after each command?使用 Node.js,如何在子进程上执行多个命令并在每个命令后获得响应?
【发布时间】:2015-03-04 19:52:44
【问题描述】:

我正在尝试使用 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_process 类型似乎都希望在每个命令之后响应并退出,否则它只会挂起直到超时或程序关闭。

我喜欢下面这样的某种功能。

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”的测试文件

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

【问题讨论】:

    标签: node.js shell


    【解决方案1】:

    您必须停止使用同步命令。这是一个玩具示例:

    我正在调用这个程序,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-09
      • 2015-10-07
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      相关资源
      最近更新 更多