The path used to load the library.
Node.js module
node:ffi
enum types
- ARRAY_BUFFER = 'arraybuffer'
- BOOL = 'bool'
- BUFFER = 'buffer'
- CHAR = 'char'
- DOUBLE = 'double'
- FLOAT = 'float'
- FLOAT_32 = 'float32'
- FLOAT_64 = 'float64'
- FUNCTION = 'function'
- INT_16 = 'int16'
- INT_32 = 'int32'
- INT_64 = 'int64'
- INT_8 = 'int8'
- POINTER = 'pointer'
- STRING = 'string'
- UINT_16 = 'uint16'
- UINT_32 = 'uint32'
- UINT_64 = 'uint64'
- UINT_8 = 'uint8'
- VOID = 'void'
class DynamicLibrary
- readonly symbols: {}__index[symbol: string]: bigint;
An object containing previously resolved symbol addresses as
bigintvalues. Calls
library.close(). This allowsDynamicLibraryinstances to be used with theusingdeclaration for automatic cleanup when the enclosing scope exits. It is a no-op on a library that has already been closed.Closes the library handle.
DynamicLibraryimplements the explicit resource management protocol, so a library instance can be managed with theusingdeclaration. Leaving the enclosing scope invokeslibrary.close()automatically.import { DynamicLibrary } from 'node:ffi'; { using lib = new DynamicLibrary('./mylib.so'); // Use `lib` here; `lib.close()` is called when the block exits. }Calling
library.close()(or disposing the library) more than once is a no-op.After a library has been closed:
- Resolved function wrappers become invalid.
- Further symbol and function resolution throws.
- Registered callbacks are invalidated.
Closing a library does not make previously exported callback pointers safe to reuse. Node.js does not track or revoke callback pointers that have already been handed to native code.
If native code still holds a callback pointer after
library.close()or afterlibrary.unregisterCallback(pointer), invoking that pointer has undefined behavior, is not allowed, and is dangerous: it can crash the process, produce incorrect output, or corrupt memory. Native code must stop using callback addresses before the library is closed or before the callback is unregistered.Calling
library.close()from one of the library's active callbacks is unsupported and dangerous. The callback must return before the library is closed.- name: string,signature: T
Resolves a symbol and returns a callable JavaScript wrapper.
The returned function has a
.pointerproperty containing the native function address as abigint.If the same symbol has already been resolved, requesting it again with a different signature throws.
const { DynamicLibrary } = require('node:ffi'); const lib = new DynamicLibrary('./mylib.so'); const add = lib.getFunction('add_i32', { arguments: ['i32', 'i32'], return: 'i32', }); console.log(add(20, 22)); console.log(add.pointer); When
definitionsis provided, resolves each named symbol and returns an object containing callable wrappers.When
definitionsis omitted, returns wrappers for all functions that have already been resolved on the library.definitions: TWhen
definitionsis provided, resolves each named symbol and returns an object containing callable wrappers.When
definitionsis omitted, returns wrappers for all functions that have already been resolved on the library.Returns an object containing all previously resolved symbol addresses.
- callback: () => void): bigint;
Creates a native callback pointer backed by a JavaScript function.
When
signatureis omitted, the callback uses a defaultvoid ()signature.The return value is the callback pointer address as a
bigint. It can be passed to native functions expecting a callback pointer.const { DynamicLibrary } = require('node:ffi'); const lib = new DynamicLibrary('./mylib.so'); const callback = lib.registerCallback( { arguments: ['i32'], return: 'i32' }, (value) => value * 2, );Callbacks are subject to the following restrictions:
- They must be invoked on the same system thread where they were created.
- They must not throw exceptions.
- They must not return promises.
- They must return a value compatible with the declared return type.
- They must not call
library.close()on their owning library while running. - They must not unregister themselves while running.
Closing the owning library or unregistering the currently executing callback from inside the callback is unsupported and dangerous. Doing so may crash the process, produce incorrect output, or corrupt memory.
signature: T,): bigint;Creates a native callback pointer backed by a JavaScript function.
When
signatureis omitted, the callback uses a defaultvoid ()signature.The return value is the callback pointer address as a
bigint. It can be passed to native functions expecting a callback pointer.const { DynamicLibrary } = require('node:ffi'); const lib = new DynamicLibrary('./mylib.so'); const callback = lib.registerCallback( { arguments: ['i32'], return: 'i32' }, (value) => value * 2, );Callbacks are subject to the following restrictions:
- They must be invoked on the same system thread where they were created.
- They must not throw exceptions.
- They must not return promises.
- They must return a value compatible with the declared return type.
- They must not call
library.close()on their owning library while running. - They must not unregister themselves while running.
Closing the owning library or unregistering the currently executing callback from inside the callback is unsupported and dangerous. Doing so may crash the process, produce incorrect output, or corrupt memory.
- pointer: bigint): void;
Allows the callback to become weakly referenced by JavaScript.
If the callback function is later garbage collected, subsequent native invocations become a no-op. Non-void return values are zero-initialized before returning to native code.
- pointer: bigint): void;
Releases a callback previously created with
library.registerCallback().Calling
library.unregisterCallback(pointer)for a callback that is currently executing is unsupported and dangerous. The callback must return before it is unregistered.After
library.unregisterCallback(pointer)returns, invoking that callback pointer from native code has undefined behavior, is not allowed, and is dangerous: it can crash the process, produce incorrect output, or corrupt memory.
- const suffix: string
The native shared library suffix for the current platform:
'dylib'on macOS'so'on Unix-like platforms'dll'on Windows
This can be used to build portable library paths:
const { suffix } = require('node:ffi'); const path = `libsqlite3.${suffix}`; - ): void;
Closes a dynamic library.
This is equivalent to calling
handle.close(). - path: null | string,definitions?: T
Loads a dynamic library and resolves the requested function definitions.
On Windows passing
nullis not supported.When
definitionsis omitted,functionsis returned as an empty object until symbols are resolved explicitly.The returned object also implements the explicit resource management protocol, so it can be used with the
usingdeclaration. Disposing the returned object closes the library handle.import { dlopen } from 'node:ffi'; { using handle = dlopen('./mylib.so', { add_i32: { arguments: ['i32', 'i32'], return: 'i32' }, }); console.log(handle.functions.add_i32(20, 22)); } // handle.lib.close() is invoked automatically here.import { dlopen } from 'node:ffi'; const { lib, functions } = dlopen('./mylib.so', { add_i32: { arguments: ['i32', 'i32'], return: 'i32' }, string_length: { arguments: ['pointer'], return: 'u64' }, }); console.log(functions.add_i32(20, 22));@param pathPath to a dynamic library, or
nullto resolve symbols from the current process image.@param definitionsSymbol definitions to resolve immediately.
- symbol: string): bigint;
Resolves a symbol address from a loaded library.
This is equivalent to calling
handle.getSymbol(symbol). - pointer: bigint,length: number): void;
Copies bytes from an
ArrayBufferinto native memory.lengthmust be at leastarrayBuffer.byteLength.pointermust refer to writable native memory with at leastlengthbytes of available storage. This function does not allocate memory on its own. - arrayBufferView: ArrayBufferView,pointer: bigint,length: number): void;
Copies bytes from an
ArrayBufferViewinto native memory.lengthmust be at leastarrayBufferView.byteLength.pointermust refer to writable native memory with at leastlengthbytes of available storage. This function does not allocate memory on its own. - pointer: bigint,length: number): void;
Copies bytes from a
Bufferinto native memory.lengthmust be at leastbuffer.length.pointermust refer to writable native memory with at leastlengthbytes of available storage. This function does not allocate memory on its own.buffermust be a Node.jsBuffer. - string: string,pointer: bigint,length: number,encoding?: BufferEncoding): void;
Copies a JavaScript string into native memory and appends a trailing NUL terminator.
lengthmust be large enough to hold the full encoded string plus the trailing NUL terminator. For UTF-16 and UCS-2 encodings, the trailing terminator uses two zero bytes.pointermust refer to writable native memory with at leastlengthbytes of available storage. This function does not allocate memory on its own.stringmust be a JavaScript string.encodingmust be a string.@param encodingDefault:
'utf8'. - ): bigint;
Returns the raw memory address of JavaScript-managed byte storage.
This is unsafe and dangerous. The returned pointer can become invalid if the underlying memory is detached, resized, transferred, or otherwise invalidated. Using stale pointers can cause memory corruption or process crashes.
- pointer: bigint,length: number,copy?: boolean
Creates an
ArrayBufferfrom native memory.When
copyistrue, the returnedArrayBuffercontains copied bytes. Whencopyisfalse, the returnedArrayBufferreferences the original native memory directly.The same lifetime and bounds requirements described for
ffi.toBuffer(pointer, length, copy)apply here. Withcopy: false, the returnedArrayBufferis a zero-copy view of foreign memory and is only safe while that memory remains allocated, unchanged in layout, and valid for the entire exposed range.@param copyWhen
false, creates a zero-copy view. Default:true. - pointer: bigint,length: number,copy?: boolean): NonSharedBuffer;
Creates a
Bufferfrom native memory.When
copyistrue, the returnedBufferowns its own copied memory. Whencopyisfalse, the returnedBufferreferences the original native memory directly.Using
copy: falseis a zero-copy escape hatch. The returnedBufferis a writable view onto foreign memory, so writes in JavaScript update the original native memory directly. The caller must guarantee that:pointerremains valid for the entire lifetime of the returnedBuffer.lengthstays within the allocated native region.- no native code frees or repurposes that memory while JavaScript still uses the
Buffer. - Memory protection is observed. For example, read-only memory pages must not be written to.
If these guarantees are not met, reading or writing the
Buffercan corrupt memory or crash the process.@param copyWhen
false, creates a zero-copy view. Default:true. - pointer: bigint): null | string;
Reads a NUL-terminated UTF-8 string from native memory.
If
pointeris0n,nullis returned.This function does not validate that
pointerrefers to readable memory or that the pointed-to data is terminated with\0. Passing an invalid pointer, a pointer to freed memory, or a pointer to bytes without a terminating NUL can read unrelated memory, crash the process, or produce truncated or garbled output.
Type definitions
interface ArgumentTypeMap
interface DataTypeMap
interface DynamicLibraryResult<T extends FunctionDefinitions>
interface FunctionDefinitions
interface FunctionSignature
interface ReturnTypeMap
interface WrappedFunction<R extends ReturnType = any, P extends readonly ArgumentType[] = any[]>
- type ArgumentType = Exclude<ReturnType, 'void'>
- type ArgumentTypesFromFunctionSignature<T extends FunctionSignature> = 'arguments' extends keyof T ? T extends { arguments: infer P } ? P : any[] : []
- type CallbackFunction<R extends ReturnType = any, P extends readonly ArgumentType[] = any[]> = (...args: { [K in keyof P]: ArgumentTypeMap[DataTypeMap[P[K]]] }) => ReturnTypeMap[DataTypeMap[R]]
- type ReturnType = { [K in keyof DataTypeMap]: K }[keyof DataTypeMap]
- type ReturnTypeFromFunctionSignature<T extends FunctionSignature> = 'return' extends keyof T ? T extends { return: infer R } ? R : any : 'void'
- type WrappedFunctionsFromDefinitions<T extends FunctionDefinitions> = { [K in keyof T]: WrappedFunctionFromSignature<T[K]> }