Here's my code from a course:
const express = require('express');
const cluster = require('cluster');
const app = express();
function delay(duration) {
const startTime = Date.now();
while(Date.now() - startTime < duration) {
//event loop is blocked...
}
}
app.get('/timer', (req, res) => {
delay(9000);
res.send(`Ding ding ding! ${process.pid}`);
});
console.log('Running server.js...');
if (cluster.isPrimary) {
console.log('Master has been started...');
cluster.fork();
cluster.fork();
} else {
console.log('Worker process started.');
app.listen(3000);
}
In the lecture when the instructor visits http://localhost:3000/timer in two different tabs simultaneously, the requests finish at about the same time. However, when I do it, the first request finishes in 9 seconds and the second one finishes another 9 seconds after the first as if the requests were processed sequentially.
I've even tried using the PM2 module in cluster mode to see if there was anything wrong with the code but the requests are still processed sequentially. I tried the solution in the following thread:
Blocking requests not running simultaneously on PM2 but it did not work for me.
Anyone have any ideas?
Related
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.
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)
So I'm trying to build a Discord bot. These types of threads tend to get downvoted a lot on stackoverflow, so I'm hoping this doesn't happen to me.
This particular feature is acting as a temporary solution to my dashboard problem. Due to the nature of glitch.com's hosting, it's supposed to fall asleep after 5 minutes of http inactivity. I solved that already by adding a script that pings the URL every 4 minutes, but that caused another issue. I think what's happening is that because that script and the bot script are constantly running, and never technically 'finish', it never lets any incoming connection actually load the webpage. So my solution to that problem was to create another glitch project that would act as the dashboard website, and transfer information from the bot project. Of course then I'd need to create more scripts that communicate with each other via some internet protocol. The info recorded by the bot is all recorded in a private JSON database using the node-json-db npm library.
My problem is: I don't know what protocol would be best for this kind of thing. Even if I did know, then I'd have to go digging through the docs for the info I'm looking for.
My question is: What protocol should I use, and what docs do I need to read for this?
I've included some snippets of the code here:
The bot's server code (where I would add the script for communicating with the dashboard):
// server.js
// where your node app starts
// init project
const express = require('express');
const app = express();
const JsonDB = require('node-json-db');
const db = new JsonDB("myDataBase", true, true);
// we've started you off with Express,
// but feel free to use whatever libs or frameworks you'd like through `package.json`.
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
response.sendFile(__dirname + '/views/index.html');
});
app.post('/login/c3RvcCBoYWNrZXIh', function(request, response) {
var servername = request.param('servername');
var password = request.param('password');
if (db.getData("/" + servername + "/password") === password) {
response.json(db.getData("/" + servername));
} else {
response.json(null);
}
});
// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
// to keep the bot alive, since glitch puts projects to sleep after 5 mins of inactivity.
const http = require('http');
setInterval(() => {
http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 270000);
The server.js on the dashboard website:
// server.js
// where your node app starts
// init project
const express = require('express');
const app = express();
const request = require('request');
// we've started you off with Express,
// but feel free to use whatever libs or frameworks you'd like through `package.json`.
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
response.sendFile(__dirname + '/views/index.html');
});
app.post('/login', function(request, response) {
var servername = request.param('servername');
var password = request.param('password');
if ("thereisnopassword" === password) {
response.sendFile(__dirname + '/dashboard/index.html');
} else {
response.sendFile(__dirname + '/views/wronginfo.html');
}
});
// listen for requests :)
const listener = app.listen(process.env.PORT, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
I had this too, but solved it by simply putting the code to start the express server before the http loop.
// Require packages
const http = require('http');
const express = require('express');
const app = express();
// Express
app.get("/", (request, response) => {
response.sendStatus(200);
});
app.listen(process.env.PORT);
// Interval
setInterval(() => {
http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 240000);
// Bot code
const Discord = require('discord.js');
const client = new Discord.Client();
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.
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);
});
});