How to Run C Code in NodeJS?
Last Updated :
28 May, 2024
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:
By using Native Addons
To connect JavaScript and C/C++ code, Node.js offers a feature called "Native Addons.". This approach involves writing C/C++ code and compiling it into a shared library, which is then loaded into Node.js using require().
Syntax:
const addon = require('./addon');
console.log(addon.method());
Example: This example shows the execution of C file using nodejs.
C
#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello from GFG"));
}
void Initialize(Local<Object> exports) {
NODE_SET_METHOD(exports, "method", Method);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
}
JavaScript
const addon = require('./build/Release/addon');
console.log(addon.method());
Steps to run:
Step 1: Create a file called addon.cc and copy the C code into it.
Step 2: Create a file called binding.gyp in the same directory with the following content:
{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ]
}
]
}
Step 3: Open a terminal, navigate to the directory containing addon.cc and binding.gyp, and run the following commands to build the addon:
node-gyp configure
node-gyp build
Step 4: Create a file called app.js and copy the JavaScript code into it.
Step 5: Run the Node.js application with the following command:
node app.js
Output:
OutputBy using Child Processes
Node.js offers the child_process module, allowing execution of external processes. This approach involves spawning a child process to run a compiled C program and communicating with it via standard streams
Syntax:
const { exec } = require('child_process');
exec('./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.
C
#include <stdio.h>
int main() {
printf("Hello from C\n");
return 0;
}
JavaScript
const { exec } = require('child_process');
exec('./my_c_program', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout); // Output: Hello from C
});
Steps to run:
Step 1: Create a file called my_c_program.c and copy the C code into it.
Step 2: Compile the C code with the following command:
gcc -o my_c_program my_c_program.c
Step 3: Create a file called app.js and copy the JavaScript code into it.
Step 4: Run the Node.js application with the following command:
node app.js
Output:
Output
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.
C
#include <stdio.h>
int main() {
printf("Hello from C\n");
return 0;
}
JavaScript
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:
Output
Similar Reads
How to Run Java Code in Node.js ? Running Java code within a Node.js environment can be useful for integrating Java-based libraries or leveraging Java's robust capabilities within a JavaScript application. This article will guide you through the steps required to execute Java code from a Node.js application, covering various methods
2 min read
How to Install Node & Run NPM in VS Code? Node.js is an open-source, server-side JavaScript runtime environment built on the V8 engine. It allows developers to execute JavaScript code outside of a web browser. In this article, we will see how to install Node.js and NPM and install packages in VS Code using NPM. Steps to Install NodeJS and N
2 min read
How To Compile And Run a C/C++ Code In Linux C Programming Language is mainly developed as a system programming language to write kernels or write an operating system. C++ Programming Language is used to develop games, desktop apps, operating systems, browsers, and so on because of its performance. In this article, we will be compiling and exe
4 min read
How to Install NodeJS on MacOS Node.js is a popular JavaScript runtime used for building server-side applications. Itâs cross-platform and works seamlessly on macOS, Windows, and Linux systems. In this article, we'll guide you through the process of installing Node.js on your macOS system.What is Node.jsNode.js is an open-source,
6 min read
How to Run Node Server? A Node server runs JavaScript outside the browser to handle web requests. It listens for incoming requests, processes them, and sends responses. Unlike traditional servers, it handles multiple requests at once without waiting for each to finish.Some of the key features of the Node Server are:Non-Blo
3 min read