Categories
express javascript node.js

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