Why call dynamic link libraries in Node.js
In a previous project of the company, it was necessary to call third-party interface apis, especially to communicate with hardware devices, and these interface apis were basically implemented through C++ dynamic link library (DLL)
There were two options:
- By the back-end staff to write a service to remove the call DLL, the front-end page directly by sending requests to this service for operation
- In the front part, use Node-ffi to call DLL dynamic library files directly
We ended up using the second option!
What is Node-ffi
Node FFI Tutorial
node-ffi
provides a powerful set of tools for interfacing with dynamic libraries using pure JavaScript in the Node.js environment. It can be used to build interface bindings for libraries without using any C++ code.
Precautions!
- Ffi can only call C-style modules.
- You need to build the C source code into a dynamic link library for invocation, build the C source code into a. So file under Linux, and build a. DLL file under Windows
Install Node-ffi
npm install ffi
Copy the code
How to use Node-ffi
A simple example:
- In our business, there is such an API. The parameters are a port number of type short and a baud rate of type int. If the return value is less than 0, it means failure
dc_init
int USER_API dc_init(short port, int baud);
Copy the code
- How do I use FFI to call this interface in NodeJS, whose source code has been wrapped
dcrf32.dll
This dynamic link library, we call it directly.
let ref = require('ref')
let FFI = require('ffi')
let shortType = ref.types.short
// Path to the DLL file
let dllPath = __dirname + '/dll/dcrf32.dll'
let lib = new FFI.Library(dllPath, {
'dc_init': ['int', [shortType, 'int']]})let handle = lib.dc_init(2.9600)
console.log(handle)
Copy the code
Detailed API can see about the ref their official documents: https://github.com/TooTallNate/ref