Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke external scripts/programs from node.js

Tags:

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?

like image 364
alh Avatar asked Jan 07 '14 13:01

alh


People also ask

How can we run an external process with node js?

To execute an external program from within Node. js, we can use the child_process module's exec method. const { exec } = require('child_process'); exec(command, (error, stdout, stderr) => { console. log(error, stdout, stderr) });

How do I call a node JS shell script?

Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.


1 Answers

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'); }); 
like image 123
Plato Avatar answered Oct 22 '22 12:10

Plato