I trying to restart nodejs app which is running in background screen app.
But here i can't do these without reboot my PC. I used forever module but it's start when i reboot my PC but I actually want one button on web-page and when I click on that automatically start node app without restart my PC.
Any One have iDEA about these please let me guide what to Do ?
NOTE : without reboot my system working
You can execute commands from nodejs like this :
nodejs
var child_process = require('child_process');
child_process.exec('forever restart', function callback(error, stdout, stderr) {
// console.log(stdout);
});
Related
I have a simple node-cron schedule that calls a function:
cron.schedule('00 00 00 * * *', () => {
console.log('update movies', new Date().toISOString());
updateMovies();
});
When I log in to my server using PuTTy or use the droplet console in Digital Ocean and then run the updateMovies.mjs file node server/updateMovies.mjs and wait for the time that the cron-job should run, everything works as expected.
But when I close PuTTy or the droplet console in Digital Ocean, then nothing happens when the cron-job should run. So the server seems to lose the cron-job when I close the session.
Short answer
You need to run the app in the background
nohup node server/updateMovies.mjs >/dev/null 2>&1
Long answer
Run your app directly in the shell is just for demos or academic purposes. On an enterprise environment you should a live process like a server which runs independently of the shell user.
Foreground and background processes
Processes that require a user to start them or to interact with them are called foreground processes
Processes that are run independently of a user are referred to as background processes.
How run background process (Linux)
No body uses windows for an modern deployments, so in Linux the usual strategy is to use nohup
server.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.type('text/plain');
res.send('Hell , its about time!!');
});
app.listen(process.env.PORT || 8080);
nohup node server.js >/dev/null 2>&1
If you login to the server using some shell client, and run only node server.js it will start but if you close the shell window, the process will ends.
How run background process with nodejs and PM2
pm2 server.js
More details here:
https://pm2.keymetrics.io/docs/usage/quick-start/
Best way : Docker
You need to dockerize your app and it will run everywhere with this command:
docker run -d my_app_nodejs ....
Say that I am running a process from the command line (NOT a nodejs app):
myProcess doSomething --withParam1
I am also running a nodejs app that connects to this process (rpc).
node myApp
myProcess will randomly silently fail to work properly without crashing and myApp will detect it. I need myApp to be able to restart myProcess (kill it and start it again). After I restarted myProcess, myApp will also restart itself using pm2 (I am already handling the pm2 restart part for the nodejs app - my issue is that I cannot use pm2 to restart myProcess since it is not a nodejs app). Also, I cannot change the code of myProcess since it is a 3rd party software.
How can I restart the external process from my nodejs app?
I ended up using process.kill to kill the process and nodejs child process to restart it.
To find the pid of the process before killing it, I used this:
const childProcess = require('child_process');
function printPid() {
childProcess.exec('pidof -s myProcess', function(error, stdout, stderr) {
if (error) {
console.log(error);
} else {
console.log(stdout);
}
});
}
Requirement is to fetch the output of a shell script's after running it from the Angular 4 component at the beginning during compilation i.e. just before the website is launched. I have already gone through the threads in stackoverflow i.e. 49700941 and 41637166.
From the first thread i tried to use the below code, but getting error:
Module not found: Error: Can't resolve 'child_process' in 'app/component ...'
const exec = require('child_process').exec; // Can't resolve 'child_process' error coming from this line
exec('/home/myDir/init_setup.sh', (err, stdout, stderr) => {
if (err){
console.error(err);
return;
};
console.log(stdout);
console.log(stderr);
/**
remaining logics
*/
});
Please let me know if I need to import some library explicitly or not to avoid this error.
The modern browsers opens the webpage in isolated sandbox so they have have no access to clients' computers.
Imagine the damage that could be done if a black hat could run batch script on computer that opens his webpage.
The only way to run the script is to run the desktop application on client's machine.
The example code you provided is Node.js code, the desktop framework that user have to install on his machine and run the code intentionally. There's (fortunately!) no way to run it remotely via webpage.
I've been browsing around but to no success. I've found some npm packages like nodemon and forever but documentation doesn't explain how to call a restart inside the script properly.
I've found this code snippet on another question but I'm not using Express or other frameworks since the script is using a pulling service not a response one.
This is code I've made so far using internal Node.js dependencies but no luck.
'use strict'
process.on('uncaughtException', (error) => {
console.error('Global uncaughtException error caught')
console.error(error.message)
console.log('Killing server with restart...')
process.exit(0)
})
process.on('exit', () => {
console.log('on exit detected')
const exec = require('child_process').exec
var command = 'node app.js'
exec(command, (error, stdout, stderr) => {
console.log(`error: ${error.message}`)
console.log(`stdout: ${stdout}`)
console.log(`stderr: ${stderr}`)
})
})
setTimeout(() => {
errorTriggerTimeBomb() // Dummy error for testing triggering uncaughtException
}, 3000)
Just to note I'm running the server on Termux, a Linux terminal app for android. I know it's better to run from desktop but I'm always at a WiFi or mobile data area and that I don't like leaving my PC on overnight.
A typical restart using something like nodemon or forever would be triggered by calling process.exit() in your script.
This would exit the current script and then the monitoring agent would see that it exited and would restart it for you. It's the same principal as if it crashed on its own, but if you're trying to orchestrate it shutting down, you just exit the process and then the monitoring agent will restart it.
I have a home automation server that is being monitored using forever. If it crashes forever will automatically restart it. I also have it set so that at 4am every morning, it will call process.exit() and then forever will automatically restart it. I do this to prevent any memory leak accumulation over a long period of time and 30 seconds of down time in the middle of the night for my application is no big deal.
I'm trying to run instances of console application ( written on cpp ) from nodejs by using child_process .
Here is the code :
function startSingleApp() {
console.log("startSingleApp entered");
var exec = childProcess.exec;
var appOut;
exec("./ConsoleApplication.exe" ,function callback(error, stdout, stderr){
appOut = stdOut;
console.log("started console app");
});
};
And ConsoleApplication4 only prints strings ( cout<<"some string")
Expected behavior : for each instance of ConsoleApplication4 - console window opened and new process created
Actual behavior : no console window , no process create . But "started console app" string printed on console ( from which nodejs app started )
ConsoleApplication.exe located in same folder where nodejs app located
If replace ConsoleApplication.exe by some window app ( notepad or calc) - it works.
The question - what is missing in this code ? Do I need manually catch console out from the consoleapplication ?
Your help will be helpful.
Thaks in advance
If you run a console application from a console, it’s still going to run in the same console. The Windows console is just a convenience that opens automatically when you’re running a console application through Explorer.
You can try it yourself: open cmd.exe first, then run ConsoleApplication.exe. It won’t open a new window; the output will appear beneath your prompt. And then you’ll get another one.
If you want a window to show up, you can run cmd manually:
exec("cmd /c ConsoleApplication.exe", function callback(error, stdout, stderr) {
appOut = stdOut;
console.log("started console app");
});
You can use start to make a new console window like this:
exec("start ConsoleApplication.exe", ....)
and add a line in your C++:
getch();