确定加密支持是否不可用


【Determining if crypto support is unavailable】

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

【It is possible for Node.js to be built without including support for the node:crypto module. In such cases, attempting to import from crypto or calling require('node:crypto') will result in an error being thrown.】

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

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

let crypto;
try {
  crypto = require('node:crypto');
} catch (err) {
  console.error('crypto 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 crypto;
try {
  crypto = await import('node:crypto');
} catch (err) {
  console.error('crypto support is disabled!');
}