johnpyp
johnpyp

Reputation: 927

Isolate Node JS "apps" within a single containing server

My goal is to try to have multiple Node JS "apps" within one instance of a node js server. For example, in traditional PHP hosting, you can put different folders in the www directory and those folders will act as separate routes. If I have folder1 and folder2 as subdirectories going to www.example.com/folder1 or www.example.com/folder2 will be their own apps with their own index.html and everything.

With Node JS it is a little different because instead of calling individual server-side PHP scripts, you make calls to the main server that is running. With something like socket.io, you do socket('on'...) and socket('emit'...) to communicate with the server, not calling specific scripts but instead communicating with the server.

I want to try to mimic the PHP functionality within Node JS

This might be an example file structure:

main
|--sites
   |--site1
   |  |--index.js
   |  |--public
   |--site2
   |  |--index.js
   |  |--public
   |--landing
      |--index.js
      |--public
|--app.js

I would imagine that the app.js file would have all the routes in it. It would specify that "/" was to the landing folder, "/site1" was to site1 folder etc.

The thing I want with this is, however, that each of these "apps" is isolated. The index.js would be a server isolated to that app. The routing and everything within that app would all be done again, as if it was a fresh app.js, but they aren't separate node apps, just sub directories.

Is this possible? Can you give me some example code for implementation?

Upvotes: 0

Views: 583

Answers (1)

Keith
Keith

Reputation: 24241

If using express, you can just create multiple instances of express. And then just attach them to your main router.

eg.

Lets say you have /app1/app.js

const express = require('express');

const app = new express();
app.get('/xyz'); //etc..

module.exports = app;

And say another /app2/app.js, that basically has the same..

You could then create your main entry point to have something like ->

const app = new express();
app.use('/app1', require('./app1/app'));
app.use('/app2', require('./app2/app'));

In the above any requests to /app1/* will go to app1, and /app2/* go to app2.

Upvotes: 1

Related Questions