Search code examples
javascriptnode.jsreactjswebpackenergyplus

Execute a Node.js child process after clicking a button


At the moment I have a code in Node.js which calls the program "EnergyPlus". Unfortunately I have to start an external console and execute the Node.js file "manually". However, I would like to be able to press a button in the front end of my application that starts the "EnergyPlus" plus program.

Here is my Node.js file:

var spawn = require('child_process').spawn,
child = spawn('C:\\EnergyPlusV9-0-1\\EP-Launch.exe', ["C:/Windows/System32/Drivers/etc/hosts"]);

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

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

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

Is there a way to integrate this code within a button or to execute this code after clicking a button? Thank you very much in advance!


Solution

  • Here's how you can do this:

    1. On client side button click, make a request to a certain path in your express API
    2. Your express API handles the request by launching the program

    Code something that looks like this:

    client.html:

    <button onclick="func()">start app</button>
    <script>
      const func = () => fetch('http://your.api.url/some/path');
    </script>
    

    server.js:

    // imports
    const express = require('express');
    const spawn = require('child_process').spawn;
    
    // create server
    const app = express();
    
    // upon request to the launch path, launch the program
    app.get('/some/path', (req, res) => {
    
      let child = spawn(
        'C:\\EnergyPlusV9-0-1\\EP-Launch.exe',
        ["C:/Windows/System32/Drivers/etc/hosts"]
      );
      // etc (rest of the code you wrote)
    
      // response. You can modify this to send a custom response to your client
      res.send('');
    })