Writing Node.js modules in C++

Today I found myself looking at how to write node.js modules in C++. I read @izs’s article on the How to Node website and felt tempted to explore the C++ route, being already familiar with their JavaScript counterparts.

I am no C++ expert, in fact I’m quite a noobie, but I have read a lot of it (it is used to ilustrate programming concepts in sooooo many books) and even managed to write a couple of command line tools for my own use. Anyway, the idea in this post is to show the most basic interaction between a C++ module and node.js. The examples I have seen have been very useful, but I felt the need to simplify the code even more and reduce the “hello world” module into the bare minimum.

So this is my go at it:

This code registers a module called cpphello. This module has one method called foo, and this method simply returns a string (“Hello World”).

UPDATE: This example has been updated thanks to pull requests from kul

So from a node.js JavaScript file we could use it like this:

You can get the whole source code for this hello world module from GitHub (https://github.com/lupomontero/node-cpphello). There you will find the .cpp file with the c++ source and a JavaScript file using the module together with the build script.

Ok, so now that I have a basic hello world module I can’t help but wondering, how much faster will the C++ code run? Well, at this point I just had to, so I wrote a really quick and dirty test. The test implements the exact same piece of code both in C++ and JavaScript and then compares execution times. You can download the test also from GitHub: https://github.com/lupomontero/node-cppspeed.

The results:

foo run in 167ms
cppfoo run in 18ms
c++ was 9.3 times faster

Other examples:

https://github.com/pkrumins/node-async
https://github.com/isaacs/node-async-simple

Categories: Uncategorized
  • http://www.calbertts.com/ Carlos Alberto CastaƱo G.

    Thanks!..

  • Pingback: Can C++ code reliably interact with other C++ code? | BlogoSfera()

  • Imran Khan

    Good example.

    I’m curious, if I wanted to extend this example to say have cpphello.foo() be called from a web browser and have the contents of the string be displayed in a header/paragraph tag would I need some sort of intermediary code?

  • Jayesh Choudhari

    Hey.. Nice article…
    I think node-waf is now replaced with node-gyp with some additional changes. It will be nice if you update the article.
    Thanks

  • Harald Veland

    What about if the C code was originally written in Python? Would it still be that much faster?

  • Pingback: Is it possible to write a node.js extension in C (not C++)? - DexPage()

ENOISE - WordPress Hosting