Cornelius Qualley
Cornelius Qualley

Reputation: 761

How to run function in child process in Node.js

I've been able to successfully run commands using the exec() command. However, I'd like to leave a process running and continue to run commands on the open process, then close on app exit. Take this generic code:

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

exec("XR_Command -i 192.168.0.100 -f /ch/01/on | kill", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

I would like to keep the XR_Command process active so that I can issue commands to the active process. So, basically I would like to do this:

> XR_Command -i 192.168.0.100

> /ch/01/on
> /ch/02/on
> /ch/03/on

I cannot for the life of me figure out how to make this function properly by referencing the existing child process. Thanks!

Upvotes: 0

Views: 1783

Answers (1)

Cornelius Qualley
Cornelius Qualley

Reputation: 761

Okay, so after a day I figured out two main problems I was running in to, here is my working code:

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

let Command = spawn('X_Control', ['-i', '192.168.0.1']);
Command.stdout.pipe(process.stdout);
Command.stderr.pipe(process.stderr);

Command.stdin.write('some command\n');

Command.on('error', function(err) {
    console.error(err);
});

Command.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
});

Command.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

Issue 1: My application command was X_Control -i 192.168.0.1, every space needs to be quoted separately as Command = spawn('X_Control', ['-i', '192.168.0.1']); This took me a while to track down.

Issue 2: Command.stdin.write('some command\n'); is how I execute commands on my running application, and it must be followed by \n in order to execute the command.

Upvotes: 2

Related Questions