How to invoke external scripts/programs from node.js

前端 未结 2 613
死守一世寂寞
死守一世寂寞 2020-12-04 08:33

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

相关标签:
2条回答
  • 2020-12-04 09:17

    Might be a old question but some of these references will provide more details and different ways of including python in NodeJS.

    There are multiple ways of doing this.

    • first way is by doing npm install python-shell

    and here's the code

    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
    

    you can send a message to python shell using pyshell.send('hello');

    you can find the API reference here- https://github.com/extrabacon/python-shell

    • second way - another package you can refer to is node python , you have to do npm install node-python

    • third way - you can refer to this question where you can find an example of using a child process- How to invoke external scripts/programs from node.js

    a few more references - https://www.npmjs.com/package/python

    if you want to use service-oriented architecture - http://ianhinsdale.com/code/2013/12/08/communicating-between-nodejs-and-python/

    0 讨论(0)
  • 2020-12-04 09:25

    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');
    });
    
    0 讨论(0)
提交回复
热议问题