node js listen on multiple ports code example

Example 1: how to run multple port node

var http=require('http');
var url = require('url');
var ports = [7006, 7007, 7008, 7009];
var servers = [];
var s;
function reqHandler(req, res) {
        var serPort=req.headers.host.split(":");
        console.log("PORT:"+serPort[1]);//here i get it using http header.
}
ports.forEach(function(port) {
    s = http.createServer(reqHandler);
    s.listen(port);
    servers.push(s);
});

Example 2: how to run multple port node

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

Tags:

Misc Example