I'm trying to integrate an external C++ library (I have access to the .so file as well as the header files) into my Node.js application.
After a lot of research my options are reduced to:
Writing a Node addon
Use node-ffi
From node-ffi's gitHub's definition I can't tell if it will or will not work directly on C++ libraries:
node-ffi is a Node.js addon for loading and calling dynamic libraries using pure JavaScript. It can be used to create bindings to native libraries without writing any C++ code.
So the questions I have are:
I'm no expert when it comes to C/C++ so if I missed something basic for you to be able to answer please let me know so I can improve my question.
js Foreign Function Interface for N-API. node-ffi-napi is a Node. js addon for loading and calling dynamic libraries using pure JavaScript. It can be used to create bindings to native libraries without writing any C++ code.
js Addons are dynamically-linked shared objects, written in C++, that can be loaded into Node. js using the require() function, and used just as if they were an ordinary Node. js module. They are used primarily to provide an interface between JavaScript running in Node.
libuv: libuv is a C library originally written for Node. js to abstract non-blocking I/O operations. Event-driven asynchronous I/O model is integrated. It allows the CPU and other resources to be used simultaneously while still performing I/O operations, thereby resulting in efficient use of resources and network.
There is pretty easy way to link any your library(.so .dll .a
). You should add library with correct path in binging.gyp
file:
{
"targets": [
{
"target_name": "addon",
"sources": [ "hello.cc" ],
"libraries": [
"path/toYourLibrary/yourLibName.dll or yourLibName.so"
]
}
]
}
Also there is more simpler way to write good addons using nan
. Check link for more information github link
node-ffi seems to be primarily for C programs. I went through this in the last week, and found much better luck with node addons. What you have to do is write a shim between the C++ code in the library and node.js. In my case, I needed to encode and decode packets for a security protocol, so I made node buffers that contained the packets, and wrote C++ code that got the data out of the buffers, then send the data to my C code that encoded and decoded packets.
This page: http://luismreis.github.io/node-bindings-guide/docs/returning.html has some great examples of how to get data in and out of node.js buffers in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With