Home > Software design >  What is the difference between import crypto from 'crypto' vs just using crypto in Node?
What is the difference between import crypto from 'crypto' vs just using crypto in Node?

Time:11-20

I want to use crypto to get a UUID in my new Node project. I found a solution to use crypto for that and I found out that crypto itself is a declared variable already without importing it. So both are possible:

import crypto from 'crypto'
const mything = crypto

and also without the import just:

const mything = crypto

Is there a difference?

CodePudding user response:

If you don't import it, it doesn't exist (at least as of Node.js v17.1.0), so without the import it's an error. (But see below.) There is no crypto listed in Node's documentation of its globals, and a quick test shows that crypto is indeed not defined unless you import it.

If you do node example.js with this file, for instance, you get undefined:

console.log(typeof crypto);

(But again, see below.)

Note that this is different from the browser environment. In the browser environment, crypto is a predefined global.

This may change on the Node.js side, as the environment continues to evolve toward full compatibility with web APIs. At some point, it's possible crypto will get added to Node.js's predefined globals. But it isn't (yet). But if it does change, it will be the web crypto API, not the one from the crypto module.

ruohola points out that if you use the REPL, crypto is predefined:

node
Type ".help" for more information.
> typeof crypto
'object'
> crypto === require("crypto")
true

As you can see, the object available via the crypto global available in the REPL is the same as the module you get from require("crypto").

  • Related