FFI#

Stability: 1 - Experimental

The node:ffi module provides an experimental foreign function interface for loading dynamic libraries and calling native symbols from JavaScript.

This API is unsafe. Passing invalid pointers, using an incorrect symbol signature, or accessing memory after it has been freed can crash the process or corrupt memory.

To access it:

import ffi from 'node:ffi';
const ffi = require('node:ffi');
javascript

This module is only available under the node: scheme in builds with FFI support and is gated by the --experimental-ffi flag.

Building Node.js with node:ffi support is available via the bundled libffi on platforms where libffi provides a compatible static backend, or via a shared libffi using the --shared-ffi configure flag. The unofficial GN build does not support node:ffi.

The following targets are not supported by bundled libffi:

  • s390x.
  • mips, mipsel, and mips64el on targets other than FreeBSD, Linux, and OpenBSD.
  • ppc64 on Android, CloudABI, iOS, OpenHarmony, OS/400, Solaris, and Windows.

When using the Permission Model, FFI APIs are restricted unless the --allow-ffi flag is provided.

Overview#

The node:ffi module exposes two groups of APIs:

  • Dynamic library APIs for loading libraries, resolving symbols, and creating callable JavaScript wrappers.
  • Raw memory helpers for reading and writing primitive values through pointers, converting pointers to JavaScript strings, Buffer instances, and ArrayBuffer instances, and for copying data back into native memory.

Type names#

FFI signatures use string type names.

Supported type names:

  • void
  • char
  • int8
  • uint8
  • int16
  • uint16
  • int32
  • uint32
  • int64
  • uint64
  • float32
  • float64
  • pointer
  • string
  • buffer
  • arraybuffer
  • function
Alternative spellings
  • i8 for int8
  • u8 and bool for uint8
  • i16 for int16
  • u16 for uint16
  • i32 for int32
  • u32 for uint32
  • i64 for int64
  • u64 for uint64
  • f32 and float for float32
  • f64 and double for float64
  • ptr for pointer
  • str for string

These type names are also exposed as constants on ffi.types:

  • ffi.types.VOID = 'void'
  • ffi.types.POINTER = 'pointer'
  • ffi.types.BUFFER = 'buffer'
  • ffi.types.ARRAY_BUFFER