Run a shell script with NodeJS

1

I need to create a page using nodejs, which will contain an "on / off" button. When I press this button I want to call the same route, but pass a parameter: on / off or 0/1, etc. When making this call, I will treat the received parameter and then execute a script called "connect.js" or "disconnect.js". These scripts will be in the same folder as the server. I figured that in "File System" there would be something like PHP's "exec ()" function, but I did not find it. In PHP, for example, something like exec( "/meu_path/meu_script.js $onOff"); could be done. How do I run a script on the Node?

    
asked by anonymous 18.07.2017 / 04:06

1 answer

1

If you want to run a script .js it is best to create functions in these scripts and make require or import of these scripts to be able to run those functions when needed.

If the scripts are not JavaScript you can do so, a suggestion that accepts several commands and runs them sequentially:

"use strict;"

var exec = require('child_process').exec;

const commands = [
	'sudo comando1',
	'sudo comando2'
];

function runCommand(cmds, cb){
	const next = cmds.shift();
	if (!next) return cb();
	exec(next, {
		cwd: __dirname
	}, (err, stdout, stderr) => {
		console.log(stdout);
		if (err && !next.match(/\-s$/)) {
			console.log('O commando "${next}" falhou.', err);
			cb(err);
		}
		else runCommand(cmds, cb);
	});
}

runCommand(commands, err => {
	console.log('Script corrido');
});

If you want to run only 1 command you can simplify and do so:

"use strict;"

var exec = require('child_process').exec;
const cmd = 'sudo comando1';

exec(cmd, {
  cwd: __dirname
}, (err, stdout, stderr) => {
  console.log(stdout);
  if (err) console.log(err);
  else runCommand(cmds, cb);
});
    
18.07.2017 / 10:26