确定加密支持是否不可用


【Determining if crypto support is unavailable】

Node.js 可以在不包含对 node:crypto 模块支持的情况下构建。在这种情况下,尝试从 node:http2 导入(import)或调用 require('node:http2') 将会抛出错误。

【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.】

使用 CommonJS 时,可以使用 try/catch 捕获抛出的错误:

【When using CommonJS, the error thrown can be caught using try/catch:】

let http2;
try {
  http2 = require('node:http2');
} catch (err) {
  console.error('http2 support is disabled!');
} 

在使用词法 ESM import 关键字时,只有在尝试加载模块之前(例如使用预加载模块)注册了 process.on('uncaughtException') 的处理程序,才能捕获该错误。

【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).】

在使用 ESM 时,如果代码有可能在未启用加密支持的 Node.js 版本上运行,考虑使用 import() 函数替代词法 import 关键字:

【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.error('http2 support is disabled!');
}