Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run c/c++ code from nodejs

Suppose I have a simple Hello, World! file in C++ or C (whatever will help me use it easier in Node.js, preferably C) and want to run it from a Node.js file. What is the most efficient way considering that the file will be used to boost the performance (changing CPU intensive functions from Node.js to C/C++)?

I came across the addons, but it seems to me, that in order to use it, I'll have to convert a lot of code to bring it to that format. Is there an easier way?

like image 799
John James Avatar asked Nov 29 '22 06:11

John James


1 Answers

I don't see why using child_process would be slower than other options.

I recommend:

// myCFile.c
#include <stdio.h>

int main(void){

    // Processor-intensive computations
    int x = 1+2+3;

    // Send to node via standard output
    printf("%d", x);

    // Terminate the process
    return 0;
}

Compile:

gcc -o myExecutable myCFile.c

And use child_process like this:

// File myNodeFile.js
const { exec } = require("child_process");
exec("./myExecutable", (error, stdout, stderr) => console.log(stdout));
like image 187
Marchingband Avatar answered Nov 30 '22 21:11

Marchingband