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

How to invoke external scripts/programs from node.js

本文关键字:外部 脚本 程序 调用 js node      更新时间:2023-10-16

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

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

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

请参阅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');
});

可能是一个老问题,但其中一些参考将提供更多细节和在 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

  • 第二种方式 - 你可以参考的另一个包是 节点 python ,你必须做npm install node-python

  • 第三种方式 - 您可以参考这个问题,您可以在其中找到使用子进程的示例-如何从节点调用外部脚本/程序.js

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

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