node.js:在新窗口中运行外部命令

时间:2012-05-29 11:52:42

标签: windows node.js external child-process

我正在编写一个node.js脚本,该脚本在后台永久运行并不时启动文件下载。我想使用WGET下载文件,因为它看起来更强大,直到我真正知道我在使用node.js做什么。

问题是我希望看到有问题的下载进度。但我找不到通过node.js启动WGET的方法,以便为WGET打开并显示一个新的shell窗口。

Node的exec和spawn函数在后台运行外部命令,让我可以访问输出流。但由于我的脚本在后台运行(隐藏),因此输出流的功能并不多。

我尝试通过运行“cmd / c wget ...”打开一个新的shell窗口,但这没有任何区别。

有没有办法通过node.js在新窗口中运行外部命令行进程?

1 个答案:

答案 0 :(得分:1)

您可以使用node-progress和Node的http客户端(或者requestT),不需要wget:

https://github.com/visionmedia/node-progress

示例:

var ProgressBar = require('../')
  , https = require('https');

var req = https.request({
    host: 'download.github.com'
  , port: 443
  , path: '/visionmedia-node-jscoverage-0d4608a.zip'
});

req.on('response', function(res){
  var len = parseInt(res.headers['content-length'], 10);

  console.log();
  var bar = new ProgressBar('  downloading [:bar] :percent :etas', {
      complete: '='
    , incomplete: ' '
    , width: 20
    , total: len
  });

  res.on('data', function(chunk){
    bar.tick(chunk.length);
  });

  res.on('end', function(){
    console.log('\n');
  });
});

req.end();

更新:

由于您希望在后台进程中执行此操作并监听下载进度(在单独的进程中或您拥有的内容),您可以使用pub-sub功能实现此目的:

  • 使用Redis,RabbitMQ或ZeroMQ等消息队列
  • 在已知端口/ UNIX域上启动TCP服务器并听取它

资源:

http://nodejs.org/api/net.html