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.
#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)
}
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:
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
Contact Us