How to run multiple express servers on different ports? - javascript

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)

Related

How to correctly call a function from Node.JS to Express.JS

I have a completed script that acts as a parser. The script is written in NodeJS and it works properly. The script returns an array of data and also saves it to my computer.
I would like to run this script from the frontend, at the click of a button. As far as I understand, I have to send a request to the server? It's suggested to use Express for the server, but I still haven't figured out how to call a third-party script from it, much less return any data from it.
Right now all I want is for my script to run when I make a request for the root directory "/" and send me a json in response (or for example a json file)
const express = require('express')
const runParser = require("./parser");
const app = express()
const port = 3000
app.get('/', async (req, res,next) => {
await runParser()
next()
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
All you need for Express is this:
const express = require('express');
const app = express();
const runParser = require("./parser");
const port = 3000;
app.get("/", (req, res) => {
runParser().then(results => {
res.json(results);
}).catch(err => {
console.log(err);
res.status(500).send("error");
});
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
And, then you can access that either by just going to:
http://localhost:3000
from your local host or
http://yourdomain.com:3000
in the browser or by issuing an ajax call to the desired URL from webpage Javascript.
I wouldn't personally put this type of activity on a GET request to / because that can be hit by things like web crawlers, search engines, etc...
It probably belongs on a POST (so crawlers won't issue it) and I'd personally put it on some pathname such as:
app.post("/runparser", (req, res) => {
// put your code here
});
And, then use a form submission or ajax call to that URL to trigger it.

Node/Express cluster not processing in parallel

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?

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');
});

What protocol should I use and what are the docs for it?

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();

Categories

Resources