Paules
Paules

Reputation: 560

How do i reboot linux from nodejs

I want to reboot/shutdown my linux OS from a node.js script. Only on things i can find are methods to stop a express server or a running function inside a script but not a way to shutdown/reboot my hole linux.

is there any way to do that?

Upvotes: 12

Views: 17324

Answers (5)

Simon Hutchison
Simon Hutchison

Reputation: 3035

The nodejs command is:

require('child_process').exec('sudo /sbin/shutdown -r now', function (msg) { console.log(msg) });

To avoid running nodejs as su you must give permission to run this command. Give permissions by creating a file under the /etc/sudoers.d/ directory, e.g.

$ sudo nano /etc/sudoers.d/mysudoersfile

Add the following lines and change pi in the below snippet to the user nodejs will be running as:

pi ALL=/sbin/shutdown
pi ALL=NOPASSWD: /sbin/shutdown

This technique can also be applied to other commands. For example if you want to allow the user (in turn nodejs) to restart networking then add the following to your sudoers file.

pi ALL=/etc/init.d/networking
pi ALL=NOPASSWD: /etc/init.d/networking

Upvotes: 11

I use the Paules reply and the reboot npm package docs, and now its working as expected.

Permissions (Linux only)

If you are to run node process under non-superuser, be sure to give node permissions to reboot the system:

sudo setcap CAP_SYS_BOOT=+ep usr/local/bin/node 

Upvotes: 0

Oren Pinsky
Oren Pinsky

Reputation: 421

Reboot package does exactly what you are asking for, and be found here:

https://www.npmjs.com/package/reboot

Upvotes: 0

Paules
Paules

Reputation: 560

thanks for so far. I got a solution thats working with that now. only it has no response that the command has been executed. For the rest it's working.

code:

console.log('loaded.....');
var exec = require('child_process').exec;

function execute(command, callback){
    exec(command, function(error, stdout, stderr){ callback(stdout); });
}



execute('shutdown -r now', function(callback){
    console.log(callback);
});

Upvotes: 4

user3159253
user3159253

Reputation: 17465

You should use child_process and a command like sudo /sbin/reboot. Also you need to configure sudo to allow node.js user run /sbin/reboot w/o a password prompt. see /etc/sudoers.

Upvotes: 0

Related Questions