How to stop node-server based interval script? - javascript

I am creating an application in Nodejs using Expressjs framework.
I was try to execute some script after every minute using setInterval() JavaScript method.
When I start my server by node app.js the script run successfully. But when I stop the server by Ctrl+c and trying to restart it then it says that the 3000 (my server port) already in use.
I cannot restart my server neither access my website. I am using Ubuntu.
I have used all the following commands but it doesn't stop.
fuser -k 3000/tcp
kill processNumber
killall node
Code:
router.get("/trackplayers", function(req, res, next ) {
// Run in every minute
setInterval(function(){
console.log('Players tracking is under process..');
}, 60000);
});
Thanks in advance!

Be sure to exit the process cleanly. The following code will gracefully terminate an express application.
var express = require("express");
var app = express();
var server = app.listen(3000);
// Respond to 'Ctrl+C'
process.on("SIGINT", function () {
// stop accepting connections
server.close(function () {
// connections are closed
// exit the process
process.exit(0);
});
});
// Server is shutting down
process.on("SIGTERM", function () {
// stop accepting connections
server.close(function () {
// connections are closed
// exit the process
process.exit(0);
});
});

Related

Execute node app in the background as service (without routes) with pm2

I'm starting to tinker with node.js server, I created a node application which keeps a database in sync, the function of this app/script is to run an async function in 5 minutes intervals, for this I'm using node-cron, so far I got it to work after I visit my express route / .
Issue is I don't want to have to visit a route to start/stop/whatever the cron job, I have read about pm2 and would like to be able to execute my application as background with it.
Ideally I'd start and stop the cron job from the command line, where can I find a tutorial on how to do this in an ubuntu server?
My app.js file looks like this:
var express = require('express');
var app = express();
//process.env.DB_HOST
app.get('/', async (req, res) =>
{
const job = new CronJob('0 */5 * * * *', function()
{
try
{
const databaseService = new DatabaseService();
databaseService.syncDB();
}
catch(err)
{
console.error(err);
}
});
job.start();
res.send('Hello world');
});
app.listen(3000, function()
{
console.log('Example app listening on port 3000!');
});
How to handle cron job without visiting route/script running from console in the background
If you want node to manage just the cronjob, remove express
const job = new CronJob('0 */5 * * * *', function(){
try
{
const databaseService = new DatabaseService();
databaseService.syncDB();
}
catch(err)
{
console.error(err);
}
});
job.start();
As #Randy Casburn mentioned, you can just run the database sync function in node and have the cron daemon schedule that for you instead of using pm2 to manage a long running node process.

Active handles in the simple Nodejs Request keeps increasing exponentially

I have written a simple node API whose sole purpose is just to notify the user that the internet is alive. I am hitting this API after every 3 seconds and it works fine till the active handles are around 4000 or less but after then my server stops responding till the time I restart the server. I am running this server through pm2. I have attached a link to the image of my server when I type "pm2 monit".Link - https://i.stack.imgur.com/zEgUd.png
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.set("Connection", "close");
res.send({status:200, message:'request received'}).end();
});
app.listen(5005, () => {
console.log('Listening on port 5005');
});

How to run multiple express servers on different ports?

Learning node from past week and got some hold on node and express. But now I am facing a problem. I am trying to run multiple express servers on different port and want them to return response after 10 seconds. After running the program, servers are starting fine but when I hit http://localhost:3000 or any of the server's url, observing following:
- on client side I am getting proper response from all servers after 10 secs
- server is getting into infinite loop and continuously printing "returning data..." after the delay of 10 secs
I tried using a function, using a js file to export the server and another class importing it and calling inside for loop. But sever is constantly printing "returning data..." after the delay of 10 secs. Below is my code:
var express = require('express');
const data = '{"key":"value"}';
const server = function (port) {
let app = express();
app.get('/', (req, res) => {
setInterval(function () {
console.log('returning data...')
res.end(data);
}, 10000); //want a delay of 10 secs before server sends a response
})
app.listen(port, () => console.log("Server listening at http://%s:%s",
"localhost", port))
}
console.log('\nStarting servers.......')
for (var i = 0; i < 5; i++) {
server(3000 + i)
}
You need to create multiple app instances from express. Below is the code snippet to start multiple server on different ports from same file.
var express = require('express');
let app1 = express();
let app2 = express();
app1.listen(3000, () => {
console.log("Started server on 3000");
});
app2.listen(3002, () => {
console.log("Started server on 3002");
});
You are using window.setInterval instead of window.setTimeout, that's why is running multiple times.
already answered: https://stackoverflow.com/a/71831233/17576982
(3 ways to start multiple servers on one run in nodejs)

How to structure an express app to run a light strip on a Raspberry Pi3

I've set up a node server on a raspberry pi to display a sequence of colors on an Adafruit Dotstar light strip. The functionality works as follows: I make an HTTP request to localhost:8000/fade, and the server responds by running the fade.js file, which is an infinite loop that fades through different colors on the light strip. Unfortunately, I'd like to be able to exit this command and shut off the light strip with another request to localhost:8000/off.
I've experimented with the child_process package in order to run the "fade" code, while also listening to new requests. However, I'm unable to kill the "fade" process.
Posted below is my app.js code. Any suggestions on how to kill the child_process, or perhaps restructure the code in some other way to accomplish the same goal? I really just need to be able to run the "fade" code continuously, while also responding to new requests.
p.s. This is my first JS project so go easy! Any help is appreciated.
app.js:
var express = require('express'),
app = express();
app.get('/', function (req, res) {
res.send('App is responding to requests');
});
app.get('/fade', function (req, res) {
var fork = require('child_process').fork;
child = fork('./sequences/fade.js');
});
app.get('/off', function (req, res) {
var fork = require('child_process').fork;
child = fork('./sequences/off.js');
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!')
})
fade.js:
console.log("running fade.js");
var dotstar = require('dotstar'),
SPI = require('pi-spi'),
sleep = require('sleep');
spi = SPI.initialize('/dev/spidev0.0');
const ledStripLength = 30;
const ledStrip = new dotstar.Dotstar(spi, {
length: ledStripLength
});
while(1) {
fade(); //where fade is a long sequence of colors
};
var child; // Outer scope, available in both functions.
app.get('/fade', function (req, res) {
var fork = require('child_process').fork;
child = fork('./sequences/fade.js');
});
app.get('/off', function (req, res) {
// (might be a good idea to check if child exists and is running first...)
child.kill('SIGHUP');
});
Also http://programmergamer.blogspot.com/2013/05/clarification-on-sigint-sigterm-sigkill.html
SIGHUP: ... A process has to explicitly handle this signal for it to work. ...
So SIGINT if you want to close without handling it on the fork side, or SIGKILL to just kill that mofo.

Node.js sockets, what happen if no FYN packet?

I have two node.js server, one of them connect via socket to the other and send data regulary.
Exemple could be:
client.js:
io = require('socket.io');
var socket = io.connect(IP_SERVER + ':' + PORT);
socket.on('connect', function () {
setInterval(socket.emit('data', new Date()), 60000);
});
server.js
var app = http.createServer(),
io = require('socket.io').listen(app);
app.listen(PORT);
io.sockets.on('connection', function(socket) {
socket.on('data', function(m) {
console.log(m);
});
});
Now, while the two are communicating, I shut down server.js (ctr-C for example). Is any event pop up in client.js? Is client.js will auto connect once server rebooted?
I ve tried on my own, by adding listener for 'end', 'error' and 'close'. None where started, but once server.js online, it got data anew... Can t I know when this happen?
UPDATE: Well, it seems it end up reconnecting, but the time it take seems random, I can t find anything about this in docs...
By default, it will try to reconnect after losing a connection. There is also a setting (reconnectionDelay) to let socket.io know how long to wait before attempting to reconnect, and there is also a setting (reconnectionDelayMax) that specifies the maximum amount of time to wait between reconnections. Each attempt increases the reconnection by the amount specified by reconnectionDelay.
Full documentation is here

Categories

Resources