[javascript] How can I use a C++ library from node.js?

How can I use a C++ library from node.js?

This question is related to javascript c++ node.js binding

The answer is


Here is an interesting article on Getting your C++ to the Web with Node.js

three general ways of integrating C++ code with a Node.js application - although there are lots of variations within each category:

  1. Automation - call your C++ as a standalone app in a child process.
  2. Shared library - pack your C++ routines in a shared library (dll) and call those routines from Node.js directly.
  3. Node.js Addon - compile your C++ code as a native Node.js module/addon.

There is a fresh answer to that question now. SWIG, as of version 3.0 seems to provide javascript interface generators for Node.js, Webkit and v8.

I've been using SWIG extensively for Java and Python for a while, and once you understand how SWIG works, there is almost no effort(compared to ffi or the equivalent in the target language) needed for interfacing C++ code to the languages that SWIG supports.

As a small example, say you have a library with the header myclass.h:

#include<iostream>

class MyClass {
        int myNumber;
public:
        MyClass(int number): myNumber(number){}
        void sayHello() {
                std::cout << "Hello, my number is:" 
                << myNumber <<std::endl;
        }
};

In order to use this class in node, you simply write the following SWIG interface file (mylib.i):

%module "mylib"
%{
#include "myclass.h"
%}
%include "myclass.h"

Create the binding file binding.gyp:

{
  "targets": [
    {
      "target_name": "mylib",
      "sources": [ "mylib_wrap.cxx" ]
    }
  ]
}

Run the following commands:

swig -c++ -javascript -node mylib.i
node-gyp build

Now, running node from the same folder, you can do:

> var mylib = require("./build/Release/mylib")
> var c = new mylib.MyClass(5)
> c.sayHello()
Hello, my number is:5

Even though we needed to write 2 interface files for such a small example, note how we didn't have to mention the MyClass constructor nor the sayHello method anywhere, SWIG discovers these things, and automatically generates natural interfaces.


Becareful with swig and C++: http://www.swig.org/Doc1.3/SWIG.html#SWIG_nn8

Running SWIG on C++ source files (what would appear in a .C or .cxx file) is not recommended. Even though SWIG can parse C++ class declarations, it ignores declarations that are decoupled from their original class definition (the declarations are parsed, but a lot of warning messages may be generated). For example:

/* Not supported by SWIG */
int foo::bar(int) {
    ... whatever ...
}

It's rarely to have a C++ class limited to only one .h file.

Also, the versions of swig supporting JavaScript is swig-3.0.1 or later.


There newer ways to connect Node.js and C++. Please, loot at Nan.

EDIT The fastest and easiest way is nbind. If you want to write asynchronous add-on you can combine Asyncworker class from nan.


You could use emscripten to compile C++ code into js.


Try shelljs to call c/c++ program or shared libraries by using node program from linux/unix . node-cmd an option in windows. Both packages basically enable us to call c/c++ program similar to the way we call from terminal/command line.

Eg in ubuntu:

const shell = require('shelljs');

shell.exec("command or script name");

In windows:

const cmd = require('node-cmd');
cmd.run('command here');

Note: shelljs and node-cmd are for running os commands, not specific to c/c++.


You can use a node.js extension to provide bindings for your C++ code. Here is one tutorial that covers that:

http://syskall.com/how-to-write-your-own-native-nodejs-extension


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to binding

Binding ComboBox SelectedItem using MVVM Binding List<T> to DataGridView in WinForm Angularjs Template Default Value if Binding Null / Undefined (With Filter) Bootstrap control with multiple "data-toggle" How does the 'binding' attribute work in JSF? When and how should it be used? WPF Binding to parent DataContext How to get evaluated attributes inside a custom directive How can I use a C++ library from node.js? bind/unbind service example (android) Datagrid binding in WPF