Skip to content
Advertisement

run a few node.js web servers from within a node.js application

I would like to control a few web sites using a UI to start and stop them, changing the ports that the different web server’s listen to.

PM2 is a command line utility to manage node sites, but does not have a user interface that I can supply my customer.

How can I run a node.js web site from within another node.js web application.

The following node.js code does not seem to do the work.

const { exec } = require('child_process');

....

exec('node app.js', (err, stdout, stderr) => {
    if (err) {
        console.log(`err: ${err}`);
        return;
    }

    // the *entire* stdout and stderr (buffered)
    console.log(`stdout: ${stdout}`);
    console.log(`stderr: ${stderr}`);
});

note: regular linux commands instead of the ‘node app.js’ command work as expected.

Advertisement

Answer

Got the following code to work in case you want to run the same: This is the code on the server that will spawn a new web server.

app.get('/start', ( req, res ) => {

    var node = spawn('node', ['app.js &'], { shell: true });

    node.stdout.on('data', function (data) {
      console.log('stdout: ' + data.toString());
    });

    node.stderr.on('data', function (data) {
      console.log('stderr: ' + data.toString());
    });

    node.on('exit', function (code) {
      console.log('child process exited with code ' + 
        code.toString());
    });

    // Notify client 
   res.status(200).send( {} );
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement