如何从node.js调用外部脚本/程序

时间:2014-01-07 13:23:57

标签: python c++ node.js

我有一个C++程序和一个Python脚本,我希望将其合并到我的node.js网络应用中。

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

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

2 个答案:

答案 0 :(得分:38)

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

// 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');
});

答案 1 :(得分:1)

可能是一个古老的问题,但是其中一些参考文献将提供更多详细信息以及在NodeJS中包括python的不同方式。

有多种方法可以做到这一点。

  • 第一种方法是进行npm install python-shell

这是代码

var PythonShell = require('python-shell');
//you can use error handling to see if there are any errors
PythonShell.run('my_script.py', options, function (err, results) { 
//your code

您可以使用以下命令向python shell发送消息 pyshell.send('hello');

您可以在此处找到API参考- https://github.com/extrabacon/python-shell

更多参考资料- https://www.npmjs.com/package/python

如果要使用面向服务的体系结构- http://ianhinsdale.com/code/2013/12/08/communicating-between-nodejs-and-python/

相关问题