How to Optimize Node.js with C++ Addons

15 May 2024

Node.js is one of the most widely used programming languages and frameworks and my preferred choice as a software engineer when it comes to building complex back-end structures. Choosing between Node.js and Python can be difficult as they both have their own pros and cons, however, by choosing it you may compromise on something but you can make up for that with different optimizations.

This JavaScript framework is used in building high-performance scalable applications. Node.js’ I/O model is event-driven and non-blocking, making it a popular choice for I/O applications. However, just like any other language or framework, Node.js code needs to be written efficiently and optimized to achieve maximum performance. In this article, we’ll look at some of the best ways to optimize Node.js code for increased speed, scalability, and resource efficiency.

Let's make a service using Node.js to create ‘QR codes’(CPU-intensive task) to understand how we can use C++ for optimizations.

Results for generating 10000 QR codes:

C++ single thread: 2960.125ms

Nodejs: 19180.051ms

Node js code to generate QR codes:

Following steps for C++:

Step 1: package.json

We need to add “gypfile” flag as true and dependencies.

Step 2: Create DataProcessingAsyncWorker.h (addon folder)

Header file that we will need further.

Step 3: Create (addon folder)

Here, we write processing logic.

Step 4: Create (addon folder)

Here, we have a C++ function (ProcessData), which we can call from javascript and which will execute our main processing logic on a separate thread by adding it to the worker queue.

Step 5: Install C++ dependencies

Step 6: Create binding.gyp

Step 7: Npm install

Npm install will build C++ files, and it can be used in node js as follows:

And we are done with the code walkthrough!

Every request will be added to a new thread. Let's try with 2 concurrent requests for 50,000 and 40,000 codes.

Here, we can see the parallel processing of 2 requests on separate threads(Multithreading).

We saw how easy it is to optimize node js for CPU-intensive tasks using C++.

Source code: