DEV Community

CamelJohn
CamelJohn

Posted on

NodeJS To Run C++ Executable

So, I've been working on a cool project involving:

  1. Raspberry PI
  2. NodeJS
  3. Linux (Raspbian)
  4. LibCEC (cec-client)
  5. PM2

and many more goodies.

during the process I've encountered a few bugs.

I have a NodeJS instance being run by PM2 on a linux machine (Raspberry PI) & I need to pass linux various commands.
One of them being a long runing process (hopefully forever) without closing that process, and yet run other non-blocking code.

most of my commands to the Raspberry PI will be bash commands.

so I dove into child process (comes with Node out of the box).

the child process has a few functions - that allow you to pass bash commands or run a local file (be it a .cpp file, or a .sh file).

so how would i do all of this ?

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

const compiler = "g++";
const version = "-std=c++11";
const out ="-o";
const infile = "code-runner.cpp";
const outfile = "code-runner.out";
const command = "hello world";

execFile(compiler, [version,infile, out, outfile], (err, stdout, stderr) => {
  if (err) {
    console.log(err);
  } else {
    let executable = `./${outfile}`;
    execFile(executable, (err, stdout, stderr) => {
      if (err) {
        console.log(err);
      } else {
        execFile("echo", [command], { shell: true }, (err, stdout, stderr) => {
          if (err) {
            console.log(err);
          } else {
            console.log(`what is printed to the console: ${stdout}`);
          }
        });
      }
    })
  }
})
Enter fullscreen mode Exit fullscreen mode

what we are looking at is missing some code, in my case i chose to use some c++ (nothing fancy):

#include <iostream>

int main(int argc, const char* argv[]) {
  auto input = "";

  if (argc > 1) {
    input = argv[1];
  }

  std::cout << input << std::endl;
}
Enter fullscreen mode Exit fullscreen mode

bassically the first Node code is using the execFile command, to compile the c++ file, and then run it and pass some arguments to it (in this case the echo command, with hello world as an argument).

the c++ code takes the second argument and prints it out to the console.

of course there are various ways of doing so.

but this should be a good start.

hope you enjoyed this one.

at some point I might do a series on the whole Child Process module, as well as he Cluster Module, and a few mor Node goodies.

Top comments (0)