如何从node.js调用外部脚本/程序 [英] How to invoke external scripts/programs from node.js

查看:175
本文介绍了如何从node.js调用外部脚本/程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C ++ 程序和 Python 脚本, > node.js web应用程序。

I have a C++ program and a Python script that I want to incorporate into my node.js web app.

我想使用它们来解析上传到我的网站的文件;它可能需要几秒钟的处理,所以我会避免阻止应用程序以及。

I want to use them to parse the files that are uploaded to my site; it may take a few seconds to process, so I would avoid to block the app as well.

我如何才能接受该文件,然后只需在子流程中运行 C ++ 程序和脚本 node.js 控制器?

How can I just accept the file then just run the C++ program and script in a sub-process from a node.js controller?

推荐答案

请参阅 child_process 。这里是一个使用 spawn 的示例,它允许您写入stdin并在输出数据时读取stderr / stdout。如果您不需要写入stdin,并且可以在进程完成时处理所有输出, child_process.exec 提供稍短的语法来执行命令。

see child_process. here is an example using spawn, which allows you to write to stdin and read from stderr/stdout as data is output. If you have no need to write to stdin and you can handle all output when the process completes, child_process.exec offers a slightly shorter syntax to execute a command.

// with express 3.x
var express = require('express'); 
var app = express();
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
app.post('/upload', function(req, res){
   if(req.files.myUpload){
     var python = require('child_process').spawn(
     'python',
     // second argument is array of parameters, e.g.:
     ["/home/me/pythonScript.py"
     , req.files.myUpload.path
     , req.files.myUpload.type]
     );
     var output = "";
     python.stdout.on('data', function(data){ output += data });
     python.on('close', function(code){ 
       if (code !== 0) {  
           return res.send(500, code); 
       }
       return res.send(200, output);
     });
   } else { res.send(500, 'No file found') }
});

require('http').createServer(app).listen(3000, function(){
  console.log('Listening on 3000');
});

这篇关于如何从node.js调用外部脚本/程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆