I need to simulate four servers (with different host and port) on the same nodejs instance.
An example could be:
domain1:8000 - domain2:8010 - domain3:8020 - domain4:8030 -
Can anybody please help me? Thanks
const express = require("express");
const server1 = express();
const server2 = express();
const server3 = express();
server1.listen(8000, () => {
console.log("Server 1 is up and running on port 8000");
})
server2.listen(8010, () => {
console.log("Server 2 is up and running on port 8010");
})
server3.listen(8020, () => {
console.log("Server 3 is up and running on port 8020");
})
express()
creates and returns an instance of a server. call it multiple times to create multiple instances. listen on different ports. that's all.
I add an example with a possible solution for 2 servers using node.
First, you need to create a project:
mkdir simulate4servers
cd simulate4servers
npm init (entry point: index.js)
Install Express:
npm install express --save
Put the next files into the directory:
File app.js:
'use strict';
const express = require('express');
const app = express();
const routes = require('routes.js');
app.use('/',routes);
module.exports = app;
File app2.js:
'use strict';
const express = require('express');
const app2 = express();
const routes = require('routes2.js');
app2.use('/',routes);
module.exports = app2;
File configDomain1.js:
module.exports = {
port: 8000
}
File configDomain2.js:
module.exports = {
port: 8010
}
File routes.js:
'use strict';
const express = require('express');
const api = express.Router();
api.get('/', (req,res)=>{
res.send({message: 'Hello World!'});
});
module.exports = api;
File routes2.js:
'use strict';
const express = require('express');
const api = express.Router();
api.get('/', (req,res)=>{
res.send({message: 'Hello World 2!'});
});
module.exports = api;
File index.js:
'use strict';
const app = require('./app')
const app2 = require('./app2')
const config = require('./configDomain1');
const config2 = require('./configDomain2');
app.listen(config.port, () => {
console.log(`API REST running in http://localhost:${config.port}`);
});
app2.listen(config2.port, () => {
console.log(`API REST running in http://localhost:${config2.port}`);
});
And finally, run it:
node index.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With