I have a Node.js game server and I start it by running nodemon app.js. Now, every time I edit a file the server restarts. I have implemented save and load functions and I want every time the game server restarts (due to the file chages) the game to be saved before restarting so that I can load the previous state after the restart.
Something like this is what I want:
process.on('restart', function(doneCallback) {
saveGame(doneCallback);
// The save game is async because it is writing toa file
}
I have tried using the SIGUR2 event but it was never triggered. This is what I tried, but the function was never called.
// Save game before restarting
process.once('SIGUSR2', function () {
console.log('SIGUR2');
game.saveGame(function() {
process.kill(process.pid, 'SIGUSR2');
});
});
Below code works properly in Unix machine. Now, As your saveGame is asynchronous you have to call process.kill from within the callback.
process.once('SIGUSR2', function() {
setTimeout(()=>{
console.log('Shutting Down!');
process.kill(process.pid, 'SIGUSR2');
},3000);
});
So, your code looks fine as long as you execute your callback function from within the game.saveGame() function.
// Save game before restarting
process.once('SIGUSR2', function () {
console.log('SIGUR2');
game.saveGame(function() {
process.kill(process.pid, 'SIGUSR2');
});
});
on Windows
run app like this:
nodemon --signal SIGINT app.js
in app.js add code
let process = require('process');
process.once('SIGINT', function () {
console.log('SIGINT received');
your_func();
});
Related
I'm working on a project for school in Node.js on a Raspberry Pi. I have a script that is running and will run for long periods of time controlling some LEDs. Is there a way that I can run a function when I quit the program to turn off all the LEDs I'm using (Stop power to the GPIO)?
You can handle the SIGINT (CTRL-C) signal. Something like:
function cleanup() {
// do clean up here
console.log("clean up");
}
process.on("SIGINT", () => {
cleanup();
process.exit(0);
});
say I have a long task that starts running when a person connects to InitializeDB. (Of course with authorization in the future, but left that out for now).
'post /initializeDB':'OrderController.initializeAll',
Now the problem is: the initialize function should never be run twice. - I know ideally I set up a taskmanager which just starts a task in the background which I could poll.
However for current simplicity, (and to show a proof of concept) is it possible for a sails route to "know" that another connection/route is already running? So that if I connect twice to /initializeDB it won't try to initialize the database twice?
You can use a variable in your controller - just toggle it to true when the process is running, something like that. So, in OrderController.js:
var initializeRunning = false;
module.exports = {
initializeAll: function(req, res) {
// return benign result if already running
if (initializeRunning) {
return res.send({alreadyRunning: true});
}
// start running
initializeRunning = true;
// using setTimeout as a stand-in for a long async process
setTimeout(function() {
// finished the process
res.send({complete: true});
// if you want to allow this method to run again later, unset your toggle
initializeRunning = false;
}, 3000);
},
};
We have a gulpfile with ~12 tasks, 4 of which are activated by a gulp.watch. I would like to use gulp-notify when a task started by gulp.watch completes. I don't want gulp-notify to do anything if a task is run directly. Sample code below:
const
debug = require("gulp-debug"),
gulp = require("gulp"),
notify = require("gulp-notify");
gulp.task("scripts:app", function () {
return gulp.src(...)
.pipe(debug({ title: "tsc" }))
.pipe(...); // <--- if i add notify here,
// I will always get a notification
});
gulp.task("watch", function () {
gulp.watch("ts/**/*.ts", ["scripts:app"]);
});
If I pipe to notify inside the 'scripts:app' task, it will make a notification every time that task runs, regardless of how that task was started. Again, I want to notify when the watched task completes.
I considered adding a task 'scripts:app:notify' that depends on 'scripts:app', but if possible I'd like to avoid creating "unnecessary" tasks.
I also tried the following:
gulp.watch("ts/**/*.ts", ["scripts:app"])
.on("change", function (x) { notify('changed!').write(''); });
But that results in a notification for every file changed. I want a notification when the task completes.
In other words, if I run gulp scripts:app, I should not get a notification. When I run gulp watch and change a watched file, I should get a notification.
How can I do this?
Try adding params to your build script:
function buildApp(notify){
return gulp.src(...)
.pipe(...)
.pipe(function(){
if (notify) {
//drop notification
}
});
});
}
//Register watcher
gulp.watch("ts/**/*.ts", function(){
var notify = true;
buildApp(notify);
});
//Register task so we can still call it manually
gulp.task("scripts:app", buildApp.bind(null, false));
As you can see, buildApp is a simple function. It's callable through a watcher or a "normal" task registration.
How to handle signal from external file in java script file.
i have a shell script which stops all the running process. when my node process is getting stopped or killed i want to perform some task and then allow this node to stop/kill.
i have a java script file in which i want to write this handler.
How can i catch this stop signal and perform some task before getting
killed
i have tried:
function method1(){
logger.info("this is our method to be executed before getting killed");
}
process.on('SIGTERM',method1());
you can register handle on exit
process.stdin.resume();
function exitHandler(options, err) {
//exit logic
}
process.on('exit', exitHandler.bind());
process.on('SIGINT', exitHandler.bind());
process.on('uncaughtException', exitHandler.bind());
I have a node process running that calls a node module
var monitor = require('./monitor.js');
var monitorInterval = setInterval(function () {
monitor();
console.log('running monitor')
}, 10000);
The first time this runs the monitor module but it then seems to run the interval but not the function on each subsequent 10s interval. The logs look like this.
MONITOR PROCESS STARTING
running monitor
running monitor
database connected
database connected
etc...
running monitor
running monitor
running monitor
running monitor
<10s PASS AND MONITOR DOES NOT RUN HERE>
running monitor
running monitor
<10s PASS MONITOR DOES NOT RUN HERE>
So why is this? Could it be because the JS engine is not idle? I'm pretty sure it is doing nothing during subsequent intervals.
Monitor is initialized as follows:
function Monitor() {
this._initialize();
}
module.exports = function (cb) {
if (monitor === null) {
monitor = new Monitor();
}
};
Monitor.prototype = {
_initialize: function () {
console.log('MONITOR PROCESS STARTING');
var monitor = this;
//etc
}
}