Search code examples
c++cnode.jsrequirejs

Run C or C++ code from Node.js in an efficient way


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?


Solution

  • 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));