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

alh*_*alh 22 c++ python node.js

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

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

我怎样才能接受文件,然后C++node.js控制器的子进程中运行程序和脚本?

Pla*_*ato 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');
});
Run Code Online (Sandbox Code Playgroud)