Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell script with node.js (childProcess)

I want to run a shell script on my node.js server, but nothing happened...

childProcess.exec('~/./play.sh /media/external/' + req.params.movie, function() {}); //not working

Another childProcess works perfect, but the process above won't.

childProcess.exec('ls /media/external/', movieCallback); //works

If I run the script in terminal, then it works. Any ideas? (chmod +x is set)

like image 898
Ralf Avatar asked Sep 30 '13 20:09

Ralf


People also ask

How do I run a shell script in node js?

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.

How run js file in shell script?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.

Could 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.


2 Answers

The exec function callback has error, stdout and stderr arguments passed to it. See if they can help you diagnose the problem by spitting them out to the console:

exec('~/./play.sh /media/external/' + req.params.movie,   function (error, stdout, stderr) {     console.log('stdout: ' + stdout);     console.log('stderr: ' + stderr);     if (error !== null) {       console.log('exec error: ' + error);     } }); 
like image 57
smokey.edgy Avatar answered Sep 27 '22 16:09

smokey.edgy


exec('sh ~/play.sh /media/external/' + req.params.movie ,function(err,stdout,stderr){
      console.log(err,stdout,stderr);
 })

Runs your play.sh shellscript with /media/external/+req.params.movie as argument. The output is available through stdout,stderr variables in the callback.

OR TRY THIS

var myscript = exec('sh ~/play.sh /media/external/' + req.params.movie);
myscript.stdout.on('data',function(data){
    console.log(data); // process output will be displayed here
});
myscript.stderr.on('data',function(data){
    console.log(data); // process error output will be displayed here
});`
like image 34
n_rao Avatar answered Sep 27 '22 17:09

n_rao