确定加密支持是否不可用


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

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

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

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

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

let crypto;
try {
  crypto = await import('node:crypto');
} catch (err) {
  console.log('crypto 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 crypto or calling require('node:crypto') will result in an error being thrown.

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

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