Exec would be used.
To turn off the PC:
// shutdown.js
// Require child_process
var exec = require('child_process').exec;
// Create shutdown function
function shutdown(callback){
exec('sudo /sbin/shutdown now', function(error, stdout, stderr){ callback(stdout); });
}
// Reboot computer
shutdown(function(output){
console.log(output);
});
To restart:
// reboot.js
// Require child_process
var exec = require('child_process').exec;
// Create shutdown function
function shutdown(callback){
exec('sudo /sbin/shutdown -r now', function(error, stdout, stderr){ callback(stdout); });
}
// Reboot computer
shutdown(function(output){
console.log(output);
});
Source:
link
To avoid being asked for credentials, you must give the node.js user permission to execute the task:
We create a file in /etc/sudoers.d/
that we will add the following content:
USUARIODENODEJS ALL=/sbin/shutdown
USUARIODENODEJS ALL=NOPASSWD: /sbin/shutdown
Remember to modify USUARIODENODEJS
by the corresponding user.
Greetings,