By executing shell commands
Another approach is to execute C code as if it were a shell command. This method utilizes Node.js’s `child_process` module to run the C compiler (`gcc`) and execute the compiled binary.
Syntax:
const { exec } = require('child_process');
exec('gcc -o my_c_program my_c_program.c && ./my_c_program', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
Example: This example shows the execution of C file using nodejs.
#include <stdio.h>
int main() {
printf("Hello from C\n");
return 0;
}
const { exec } = require('child_process');
exec('gcc -o my_c_program my_c_program.c &&
./my_c_program', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
Steps to run:
Step 1: Create a file called my_c_program.c and copy the C code into it.
Step 2: Create a file called app.js and copy the JavaScript code into it.
Step 3: Run the Node.js application with the following command:
node app.js
Output:
How to Run C Code in NodeJS?
Developers can take advantage of Node.js‘s robust ecosystem and performance by running C code within the framework. Child processes, Node.js extensions, and the Foreign Function Interface (FFI) can all assist in this. There is flexibility to integrate C code based on particular requirements, as each solution has its own advantages, disadvantages, and use cases.
These are the following approaches to run C code in nodeJs:
Table of Content
- By using Native Addons
- By using Child Processes
- By executing shell commands