node.jsnodejs-server

NodeJs Server: Run two different exported app.js within one http.createServer()


How can I run two app.js within hhtps.createServer() on given condition?

Or you can say two completely different node website within one http.createServer().

Below code is running only html files with on some modification. Such as folder name with correspond to website folder. For https you can create your certificate, otherwise use http.createServer instead https.createServer.

enter code hereconst path = require("path");
const fs = require('fs');
const http = require('http');
const https = require('https');
const { Server } = require("socket.io");
const static = require('node-static');

const app1 = require('./folder1/app');
const app2 = require('./folder2/app');

let folder1 = new (static.Server)('./folder1');
let folder2 = new (static.Server)('./folder2');

//Some certificate
const options = {
  key: fs.readFileSync(path.join(__dirname, './Cert') + '/folder1.com.key', 'utf8'),
  cert: fs.readFileSync(path.join(__dirname, './Cert') + '/folder_com.crt', 'utf8')
};

let server = https.createServer(options,(req, res) => {
  req.addListener('end', () => {
    try {
      let hostName = req.headers.host.split(':')[0];
      console.log(hostName);
      switch(hostName){
        case 'folder1.com':
          folder1.serve(req, res);
          break;
        case 'folder2.com':
          folder2.serve(req, res)
          break;
        default: 
          folder2.serve(req, res)
      }
    }
    catch{
      console.log(e);
    }
  }).resume();
})

const io = new Server(server, {log: false});
let port = process.env.PORT || 443;
server.listen(port);
console.log('Server is listening on port: '+ port);

Solution

  • Are you trying to expose both an http and an https endpoint?

    If so, my suggestion would be to only expose https and handle incoming http requests in your webserver such as nginx and have them redirect to https automatically.