Native Addon Loader

1.2.0 · active · verified Sun Apr 19

require-addon (version 1.2.0) is a JavaScript utility designed to facilitate the loading of native C++ addons (typically compiled as `.node` files) across various JavaScript runtimes. Its primary function is to extend the standard CommonJS `require` function by adding an `.addon` method. This package simplifies the complex process of locating and loading precompiled or dynamically compiled native modules, particularly in environments beyond standard Node.js, such as the 'bare' engine utilized within the Holepunch/Hypercore ecosystem. It aims to provide a standardized interface for consuming native bindings, abstracting away some of the underlying system-specific calls and linking complexities. The package's release cadence appears to be infrequent, which is common for foundational libraries serving a specific, critical infrastructure role. Its key differentiator is its cross-runtime compatibility, making it suitable for specialized environments where direct native module integration is essential.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the setup and basic usage of `require-addon` to load a native C++ module.

// This example demonstrates how to set up and use require-addon
// to load a native C++ module, typically compiled to a .node file.
// For a real scenario, you would have a precompiled native addon
// in your project structure.

// Step 1: Import the require-addon module using CommonJS syntax.
// The package is designed to extend the global 'require' object.
const addonLoader = require('require-addon');

// Step 2: Assign the imported function to require.addon.
// This makes the native addon loading utility available globally via 'require'.
require.addon = addonLoader;

// Step 3: Load the native addon.
// The first argument is the path to the addon's directory (often '.', meaning current directory).
// The second argument is typically __filename, providing context for resolving relative paths.
// This call will attempt to find and load the appropriate .node file for the current platform and architecture.
try {
  const bindings = require.addon('.', __filename);
  console.log('Native addon loaded successfully!');
  // Here, 'bindings' would be an object exposing functions from your C++ addon.
  // For example, if your addon had a 'hello' function:
  // console.log(bindings.hello()); // Assuming it returns a string like "Hello from C++!"
  console.log('Bindings object:', bindings);
  // In a real application, you would now call methods on the 'bindings' object.
} catch (error) {
  console.error('Failed to load native addon:', error.message);
  console.error('Ensure your native addon is correctly compiled and located.');
}

// To make this runnable, you would need an actual native addon compiled.
// This snippet primarily shows the API usage.

view raw JSON →