Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}
like image 963
technicalworm Avatar asked Dec 27 '18 12:12

technicalworm


People also ask

What port should I use for Express Server?

js/Express. js App Only Works on Port 3000. New! Save questions or answers and organize your favorite content.

Is Express server-side or client side?

It is useful for building web apps quickly on NodeJS. It is useful for building real-time applications like messaging apps. It can be used both on the client-side and server-side.


1 Answers

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");   
});
like image 171
Sreehari Avatar answered Oct 10 '22 05:10

Sreehari