Run a shell script with Nodejs

Asked

Viewed 3,849 times

1

I need to create a page using nodejs, which will contain a "Turn on/Off" button. By pressing this button I intend to make the call from the same route, but passing a parameter: on/off or 0/1, etc.. When making this call, I will treat the received parameter and then run a script called "on.js" or "off.js". These scripts will be in the same server folder. I imagined that in "File System" there would be something like PHP’s "exec()" function, but I couldn’t find it. In PHP, for example, something like exec( "/meu_path/meu_script.js $onOff");. How do I execute a script on Node?

  • I think this solves your problem https://udgwebdev.com/node-js-para-layers-child-process/

  • Rafael, grateful for the return. I think this solves the problem and found it very useful. However I ended up doing only with the require as suggested by my colleague Sergio in the other reply. I already got it that way. Thank you!

  • quiet, if solved I’m happy!

1 answer

1


If you want to run a script .js best is to create functions in these scripts and do require or import these scripts so you can run these 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);
});

  • Sergio, you’re right. only the require already solved, but anyway what you and colleague Rafael suggested about the child_processis very cool and useful. Thank you.

  • @wBB great that helped. The script I put here is for multiple commands. I have now joined a simplified version for only 1 command.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.