process.dlopen(module, filename[, flags])


process.dlopen() 方法允许动态加载共享对象。它主要由 require() 用来加载 C++ 插件,并且除非在特殊情况下,一般不应该直接使用。换句话说,除非有特定原因(例如自定义 dlopen 标志或从 ES 模块加载),否则应优先使用 require(),而不是 process.dlopen()

【The process.dlopen() method allows dynamically loading shared objects. It is primarily used by require() to load C++ Addons, and should not be used directly, except in special cases. In other words, require() should be preferred over process.dlopen() unless there are specific reasons such as custom dlopen flags or loading from ES modules.】

flags 参数是一个整数,用于指定 dlopen 的行为。详情请参阅 os.constants.dlopen 文档。

【The flags argument is an integer that allows to specify dlopen behavior. See the os.constants.dlopen documentation for details.】

调用 process.dlopen() 时,一个重要的要求是必须传入 module 实例。C++ 插件导出的函数随后可以通过 module.exports 访问。

【An important requirement when calling process.dlopen() is that the module instance must be passed. Functions exported by the C++ Addon are then accessible via module.exports.】

下面的示例展示了如何加载一个名为 local.node 的 C++ 插件,该插件导出了一个 foo 函数。通过传递 RTLD_NOW 常量,所有符号都会在调用返回前加载。在此示例中,假设该常量可用。

【The example below shows how to load a C++ Addon, named local.node, that exports a foo function. All the symbols are loaded before the call returns, by passing the RTLD_NOW constant. In this example the constant is assumed to be available.】

import { dlopen } from 'node:process';
import { constants } from 'node:os';
import { fileURLToPath } from 'node:url';

const module = { exports: {} };
dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),
       constants.dlopen.RTLD_NOW);
module.exports.foo();const { dlopen } = require('node:process');
const { constants } = require('node:os');
const { join } = require('node:path');

const module = { exports: {} };
dlopen(module, join(__dirname, 'local.node'), constants.dlopen.RTLD_NOW);
module.exports.foo();