Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Install Node & Run NPM in VS Code?
Next article icon

How to Run C Code in NodeJS?

Last Updated : 28 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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:

Screenshot-2024-05-14-232459
Output

By 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:

Screenshot-2024-05-14-233029
Output

Next Article
How to Install Node & Run NPM in VS Code?

A

affrahug38e
Improve
Article Tags :
  • JavaScript
  • Web Technologies

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 Run Cron Jobs in Node.js ?
    Cron jobs are scheduled tasks that run at specific intervals in the background, commonly used for maintenance or repetitive tasks. Users can schedule commands the OS will run these commands automatically according to the given time. It is usually used for system admin jobs such as backups, logging,
    4 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 Copy a File in Node.js?
    Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
    2 min read
  • How To Create Modules in NodeJS?
    Modules are the building blocks of NodeJS code. They help you break down your project into smaller, manageable pieces, each with its own job. To create a module, just make a JavaScript file and export what you want to share. Other files can then import and use those exports, adding that functionalit
    3 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 refresh a file in Node.js ?
    Node.js has seen an important growth in past years and is still increasing its value in many organizations and business models. Companies like Walmart or PayPal have already started to adopt it. NPM, the package manager of Node.js has been already installed when you install Node.js and is ready to r
    2 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
    7 min read
  • How to Exit Process in Node.js ?
    In this article, we will see how to exit in NodeJS application. There are different types of methods to exit in Nodejs application, here we have discussed the following four methods. Table of Content Using ctrl+C keyUsing process.exit() FunctionUsing process.exitCode variableUsing process.on() Funct
    3 min read
  • How to Handle Syntax Errors in Node.js ?
    If there is a syntax error while working with Node.js it occurs when the code you have written violates the rules of the programming language you are using. In the case of Node.js, a syntax error might occur if you have mistyped a keyword, or if you have forgotten to close a parenthesis or curly bra
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences