【问题标题】:execute a terminal command using node.js使用 node.js 执行终端命令
【发布时间】:2015-02-10 07:45:10
【问题描述】:

我正在尝试使用 node.js spawn 执行终端命令

因为我正在使用代码

console.log(args)

var child = spawn("hark", args, {cwd: workDir});
        child.stdout.on('data', function(data) {

          console.log(data.toString())        
        });

        child.stderr.on('data', function(data) {
          console.log('stdout: ' + data);

        });

        child.on('close', function(code) {
          console.log('closing code: ' + code);

        });

But it treated greater than>as string">" 和 获取输出为

tshark: Invalid capture filter "> g.xml" 

    That string isn't a valid capture filter (syntax error).
    See the User's Guide for a description of the capture filter syntax.

我如何在没有字符串的情况下使用>

【问题讨论】:

标签: abc


【解决方案1】:

您可以使用文件流将所有输出从生成的hark 放到g.xml
示例:

// don't need ">" in args
var args = [' 02:00:00:00' ,'-s','pdml'],
    logStream = fs.createWriteStream('./xml');

var spawn = require('child_process').spawn,
    child = spawn('tshark', args);

child.stdout.pipe(logStream);
child.stderr.pipe(logStream);

child.on('close', function (code) {
    console.log('child process exited with code ' + code);
});

因为child 这里是一个流,您可以将它通过管道传输到您记录的文件流中。

【讨论】:

  • 是的,还有一件事……你的编码正在工作……但它没有输出有效的 xml 文件……缺少一些属性
  • 当我使用 ctrl+C 手动退出正在运行的终端时,我将获得完整的 xml 文件。但是在代码中,我试图退出进程并杀死子进程,但没有获得完整的输出案例也
  • 尝试对child使用“退出”事件而不是“关闭”?
  • 但它没有进入'exit'事件或'close'事件..这是主要问题..我也无法确定进程是否完成,我通过 ctrl+ quil 终端c命令