c++ binding with node.js

Intro to node.js:
Node.js is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

Following are the companies which are using node.js including linkedin.


Install node.js

# git clone https://github.com/joyent/node.git
# cd node
# git checkout v0.6.18 #Try checking nodejs.org for what the stable version is
# ./configure && make && sudo make install

Now write simple code to create server- create-server.js

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");

// Listen on port 8080, IP defaults to

// Put a friendly message on the terminal
console.log("Server running at");

To execute it,

# node create-server.js

Now lets see how we can call c++ library functions from node.js

Lets create sample shared library first-


#include "shared.h"
#include <stdio.h>
#include <string>
void myclass::setx(int newx) { myx = newx; }
int  myclass::getx() { return myx; }
int myclass::square() { return myx*myx; }
std::string myclass::concatresult(int inputval,std::string inputstr)
std::stringstream ss;
ss << inputstr << inputval;
return ss.str();


#include <string>
#include <sstream>

class myclass {
   int myx;


    myclass() { myx=0; }
    void setx(int newx);
    int  getx();
    int square();
    std::string concatresult(int,std::string);

Lets compile and create shared library-

 g++ -fPIC -c shared.cpp -o shared.o
 g++ -shared  -Wl,-soname,libshared.so -o libshared.so shared.o

Now we will try to call some functions from libshared.so library with node.js code-

# mkdir node-cpphello
# cd node-cpphello

Create cpphello.cpp file -this is binding code, code which connects c++ functions and node.js-

#include <v8.h>
#include <node.h>
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <stdio.h>
#include "shared.h"

using namespace node;
using namespace v8;

static Handle foo(const Arguments& args) {
        myclass m;
        return String::New("Hello World");

extern "C" void init(Handle target) {
        NODE_SET_METHOD(target, "foo", foo);

Put shared.h file in same directory.

Now lets write compilation code in python.

Create file with name- wscript

import Options
from os import unlink, symlink, popen
from os.path import exists

srcdir = "."
blddir = "build"
VERSION = "0.0.1"

def set_options(opt):

def configure(conf):

def build(bld):
  obj = bld.new_task_gen("cxx", "shlib", "node_addon")
  obj.target = "cpphello"
  obj.source = "cpphello.cpp"
  obj.cxxflags = ["-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE"]
  obj.linkflags    = "-lshared"

def shutdown():
  if Options.commands['clean']:
    if exists('cpphello.node'): unlink('cpphello.node')
    if exists('build/Release/cpphello.node') and not exists('cpphello.node'):
      symlink('build/Release/cpphello.node', 'cpphello.node')

To compile-

# node-waf configure build

It will execute wscript and compile binding code and it will create cpphello.node file,
Here, cpphello.node is node module which we can import in node.js code and access it.

Create file cpphello.js

var cpphello = require('../cpphello');

Run it.

# node cpphello.js

You are done, Here we called setter and getter function from sample shared library with node.js.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s