Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to start multiple local node.js servers?

I'm creating an example project for an open source framework. For my demo to run, some of it's dependencies must be running local servers on other ports.

I'd rather just provide them a single command to run instead of telling them to open multiple terminals and run multiple commands in each.

What is the best/most proper/most elegant way to go about this?

like image 783
Dustin Raimondi Avatar asked Sep 29 '17 20:09

Dustin Raimondi


3 Answers

This is how I accomplish this for two web servers. You should be able to play with more &'s and fg's to get more servers.

package.json:

{
    "scripts": {
        "start": "node node_modules/something/server.js & node server.js && fg
    }
}

So the user only has to run npm install and then npm start to run two servers in one terminal and ctrl-c kills both.

Breakdown:
node node_modules/something/server.js & run this server in the background
node server.js && run my server in the foreground
fg move the most recently backgrounded shell into the foreground

like image 107
Dustin Raimondi Avatar answered Sep 21 '22 20:09

Dustin Raimondi


If you use the npm package call 'concurrently' set up your package.json file as below

you can use the following 3 commands run only server

npm run server

run only client

npm run client

run both

npm run dev

  "scripts": {
    "server": "nodemon server.js --ignore client",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },
like image 35
Michael Nelles Avatar answered Sep 21 '22 20:09

Michael Nelles


For those who want this case:

If you want to run a single script that will open multiple terminals and run different nodejs servers on each you can do something like (this is for windows.. for other os you can change command):

You can write a single nodejs file that will start all your other servers in different terminal windows

startAllServers.js:

const child_process = require('child_process');

// commands list
const commands = [
    {
        name: 'Ap1-1',
        command: 'cd ./api1 && start nodemon api1.js'
    },
    {
        name: 'Ap1-2',
        command: 'cd ./api2 && start nodemon api2.js'
    }
];

// run command
function runCommand(command, name, callback) {
    child_process.exec(command, function (error, stdout, stderr) {
        if (stderr) {
            callback(stderr, null);
        } else {
            callback(null, `Successfully executed ${name} ...`);
        }
    });
}

// main calling function
function main() {
    commands.forEach(element => {
        runCommand(element.command, element.name, (err, res) => {
            if (err) {
                console.error(err);
            } else {
                console.log(res);
            }
        });
    });
}

// call main
main();
like image 42
Vinit Narayan Jha Avatar answered Sep 22 '22 20:09

Vinit Narayan Jha