Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - How to invoke external scripts/programs from node.js

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...