确定加密支持是否不可用
可以在不支持 node:crypto
模块的情况下构建 Node.js。
在这种情况下,尝试 import
node:http2
或调用 require('node:http2')
将导致抛出错误。
使用 CommonJS 时,可以使用 try/catch 捕获抛出的错误:
let http2;
try {
http2 = require('node:http2');
} catch (err) {
console.log('http2 support is disabled!');
}
当使用词法 ESM import
关键字时,只有在尝试加载模块(例如,使用预加载模块)之前注册 process.on('uncaughtException')
的句柄时,才能捕获错误。
使用 ESM 时,如果有可能在未启用加密支持的 Node.js 版本上运行代码,则考虑使用 import()
函数而不是 import
关键字:
let http2;
try {
http2 = await import('node:http2');
} catch (err) {
console.log('http2 support is disabled!');
}
It is possible for Node.js to be built without including support for the
node:crypto
module. In such cases, attempting to import
from node:http2
or
calling require('node:http2')
will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
let http2;
try {
http2 = require('node:http2');
} catch (err) {
console.log('http2 support is disabled!');
}
When using the lexical ESM import
keyword, the error can only be
caught if a handler for process.on('uncaughtException')
is registered
before any attempt to load the module is made (using, for instance,
a preload module).
When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
import()
function instead of the lexical import
keyword:
let http2;
try {
http2 = await import('node:http2');
} catch (err) {
console.log('http2 support is disabled!');
}