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?
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 backgroundnode server.js &&
run my server in the foregroundfg
move the most recently backgrounded shell into the foreground
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\""
},
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();
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