I'm trying to restart a node.js server without any thrid party library. The bat file is executed from the node server itself.
Here is the restart.bat file:
set processId=%1
taskkill /F /PID %processId%
node app.js
Here is the code which is supposed to run the bat file:
var exec = require('child_process').exec;
exec('restart.bat ' + process.pid,
function (error, stdout, stderr) {
console.log('error: ' + error);
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
}
);
With the code above, the process is killed but the server never restart.
Can someone help please ?
PS: my node version is v8.11.4
Related
Trying to execute child_process.exe using webpack but getting error that exec is not a function. The script is working in node prompt.
test.js
const chai = require('chai');
const exec = require('child_process').exec;
describe('node version', function nodeVersion() {
it('Should display Node Version', (done) => {
exec('node -v', function(error, stdout, stderr) {
console.log('stdout: ', stdout);
console.log('stderr: ', stderr);
if (error !== null) {
console.log('exec error: ', error);
}
done();
});
});
});
Is there anyway we can execute shell commands like child_process.exec on browser?
No, there is no way to run child_process in the browser because JavaScript in the browser is not allowed to create processes. Thankfully there is no way to run a shell script in the browser, otherwise any website would have access to your machine and the bad things you could do with it are endless (e.g. delete everything with rm -rf / or at least what you've permission for).
I'd like to restart my application inside this application using NodeJS and NPM.
It doesn't work with child_process :
var exec = require('child_process').exec;
exec('npm restart', function(error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
If your Master process died, there is no way to reanimate him by himself.
Have a look at Nodemon to restart your script.
Another option: you can use forever npm module in order to start and monitor app.
So the restart function like this if from api:
app.get('/restart', function (req, res, next) {
process.exit(1);
});
Or if you are using a cluster approach you can kill the child and fork new one as shown below [checkout cluster documentation for node,
cluster.on('exit', function (worker) {
logger.info('Worker ' + worker.id + ' died :(, starting another one.');
cluster.fork();
});
I can run a bash command in node.js like so:
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", function(err, stdout, stderr) {
console.log(stdout);
});
How do I get the exit code of that command (ls -la in this example)? I've tried running
exec("ls -la", function(err, stdout, stderr) {
exec("echo $?", function(err, stdout, stderr) {
console.log(stdout);
});
});
This somehow always returns 0 regardless of the the exit code of the previous command though. What am I missing?
Those 2 commands are running in separate shells.
To get the code, you should be able to check err.code in your callback.
If that doesn't work, you need to add an exit event handler
e.g.
dir = exec("ls -la", function(err, stdout, stderr) {
if (err) {
// should have err.code here?
}
console.log(stdout);
});
dir.on('exit', function (code) {
// exit code is code
});
From the docs:
If a callback function is provided, it is called with the arguments (error, stdout, stderr). On success, error will be null. On error, error will be an instance of Error. The error.code property will be the exit code of the child process while error.signal will be set to the signal that terminated the process. Any exit code other than 0 is considered to be an error.
So:
exec('...', function(error, stdout, stderr) {
if (error) {
console.log(error.code);
}
});
Should work.
child_process.spawnSync()
This function exposes the nicest sync interface: https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options
Example:
#!/usr/bin/env node
const child_process = require('child_process');
let out;
out = child_process.spawnSync('true');
console.log('status: ' + out.status);
console.log('stdout: ' + out.stdout.toString('utf8'));
console.log('stderr: ' + out.stderr.toString('utf8'));
console.log();
out = child_process.spawnSync('false');
console.log('status: ' + out.status);
console.log('stdout: ' + out.stdout.toString('utf8'));
console.log('stderr: ' + out.stderr.toString('utf8'));
console.log();
out = child_process.spawnSync('echo', ['abc']);
console.log('status: ' + out.status);
console.log('stdout: ' + out.stdout.toString('utf8'));
console.log('stderr: ' + out.stderr.toString('utf8'));
console.log();
Output:
status: 0
stdout:
stderr:
status: 1
stdout:
stderr:
status: 0
stdout: abc
stderr:
Tested in Node.js v10.15.1, Ubuntu 19.10.
If anyone is looking for an await/Promise version:
const exec = require('util').promisify(require('child_process').exec);
let out = await exec(`echo hello`).catch(e => e);
console.log(out.stdout); // outputs "hello"
console.log(out.code); // Note: `out.code` is *undefined* if successful (instead of 0).
If the command is successful, then the it'll output an object like {stderr, stdout}. If it has a non-zero exit code, then it'll output an error object with {stderr, stdout, code, killed, signal, cmd} and the usual JavaScript Error object properties like message and stack.
In node documentation i found this information for the callback function:
On success, error will be null. On error, error will be an instance of Error. The error.code property will be the exit code of the child process while error.signal will be set to the signal that terminated the process. Any exit code other than 0 is considered to be an error.
I want to execute multiple Shell commands from a node.js application consecutively. In my case, exec(command1 & command2) does not work as it should. It works for simple commands like ls and pwd, but I need to start a server and then execute special commands on it and there, it only executes the very first command and nothing more. When I work on my command-line interface, I just type in one command after the other and I need a facility to execute them in the same manner, but automatically starting from a node.js application - and all of them in the same process!
You could use child_process module to achieve that.
Here's an example code to demonstrate the usage
var child_process = require('child_process');
var task1 = child_process.exec('node --version', function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
var task2 = child_process.exec('npm --version', function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
I am trying to create an webscket control wrapper for mplayer on beaglebone with node.js.
A glimpse of my websocket server looks lke this:
io.sockets.on('connection', function (socket)
{
SaveToLog('Client ' + clientAddress + ' connected.');
/* Function used to control the LEDs according to HTML file */
allClients.push(socket);
socket.on('miro_server', function (device, command)
{
SaveToLog(device + ' ' + command);
switch (device)
{
case 'mplayerStatus':
if(command == 'PLAYSELECTED')
{
ls = childProcess.exec('mplayer -slave -quiet -input file=/home/root/.mplayer/mplayer_fifo /home/root/agalloch.mp3',
function (error, stdout, stderr)
{
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null)
{
console.log('exec error: ' + error);
}
});
ls.on('exit', function (code)
{
console.log('Child process exited with exit code '+code);
});
}
else /* PAUSE */
{
childProcess.exec('echo "pause" > /home/root/.mplayer/mplayer_fifo',
function (error, stdout, stderr)
{
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null)
{
console.log('exec error: ' + error);
}
});
}
break;
}
});
});
The mplayer process starts correctly and I can hear music from the speakers, but the problem is that I cannot send any commands to the mplayer process via the selected fifo.
When I try the same commands in the linux terminal, it works just fine, so I presume it has something to do with the node.js process exec part.
I do not have much experience with linux or node.js, and most of the code I've written is based on code examples and tutorials.
Can anyone explain what is going on and why I cannot send playback command via fifo to the mplayer process using node.js?
Thank you.
you need to add new line to the echo command
'echo "pause" > /home/root/.mplayer/mplayer_fifo\n'
I tried this on rpi and bbb and it works info here http://sonnycruz.blogspot.com