From e7fc7a4c23576536397dc595752f7adf8cc18e18 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 3 Mar 2021 14:25:03 -0800 Subject: [PATCH] doc: crypto esm examples Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/37594 Refs: https://github.com/nodejs/node/pull/37162 Reviewed-By: Antoine du Hamel Reviewed-By: Benjamin Gruenbaum Reviewed-By: Filip Skokan --- doc/api/crypto.md | 1576 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 1377 insertions(+), 199 deletions(-) diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 96dcac7f2c460e..7c43b9ffd2f8b1 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -9,9 +9,19 @@ The `crypto` module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. -Use `require('crypto')` to access this module. +```mjs +import { createHmac } from 'crypto'; -```js +const secret = 'abcdefg'; +const hash = createHmac('sha256', secret) + .update('I love cupcakes') + .digest('hex'); +console.log(hash); +// Prints: +// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e +``` + +```cjs const crypto = require('crypto'); const secret = 'abcdefg'; @@ -26,10 +36,12 @@ console.log(hash); ## Determining if crypto support is unavailable It is possible for Node.js to be built without including support for the -`crypto` module. In such cases, calling `require('crypto')` will result in an -error being thrown. +`crypto` module. In such cases, attempting to `import` from `crypto` or +calling `require('crypto')` will result in an error being thrown. -```js +When using CommonJS, the error thrown can be caught using try/catch: + +```cjs let crypto; try { crypto = require('crypto'); @@ -38,6 +50,24 @@ try { } ``` +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: + +```mjs +let crypto; +try { + crypto = await import('crypto'); +} catch (err) { + console.log('crypto support is disabled!'); +} +``` + ## Class: `Certificate`