admin管理员组

文章数量:1194548

I'm very new to JS, I want to generate an UUID. Here's what I tried, step by step:

  1. mkdir test
  2. cd test
  3. touch file1.js
  4. Inside file1.js:

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


var uuid = crypto.randomUUID();
console.log(uuid);

I'm very new to JS, I want to generate an UUID. Here's what I tried, step by step:

  1. mkdir test
  2. cd test
  3. touch file1.js
  4. Inside file1.js:

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


var uuid = crypto.randomUUID();
console.log(uuid);

And you see the error. What is wrong? I can't find answer anywhere. Node JS version:

node -v shows v12.22.9

Share Improve this question edited Aug 2, 2022 at 9:33 Brian Brown asked Aug 2, 2022 at 9:27 Brian BrownBrian Brown 4,29118 gold badges51 silver badges82 bronze badges 8
  • 1 What version of node are you using? – mousetail 'he-him' Commented Aug 2, 2022 at 9:30
  • 2 When I run your code I get "847971d2-4a43-4744-a280-be9c6cfec4a7", meaning that it works. Double check your node version. – ZombieChowder Commented Aug 2, 2022 at 9:31
  • 2 (Side note: Your code after the try/catch should be inside the try, since if crypto support is disabled, crypto will be undefined where you're trying to use it.) – T.J. Crowder Commented Aug 2, 2022 at 9:32
  • 2 The randomUUID function was added in Node v15.6.0. You need to upgrade node. – mousetail 'he-him' Commented Aug 2, 2022 at 9:36
  • 4 @MohamedEL-Gendy It's part of the node standard library, no need to install – mousetail 'he-him' Commented Aug 2, 2022 at 9:37
 |  Show 3 more comments

4 Answers 4

Reset to default 18

here you can use randomBytes() method for get unique id

const crypto = require('crypto');
console.log(crypto.randomBytes(20).toString('hex'));

you can also use uuidv4 instead of crypto

const { uuid } = require('uuidv4');
console.log(uuid());

The error is that the crypto.randomUUID function was added for Node versions > v14.17.0.

That is according to the official docs: https://nodejs.org/api/crypto.html#cryptorandomuuidoptions

So probably your best choice, if you do not want to use newer Node versions, would be to use https://www.npmjs.com/package/uuid

I upgraded NodeJS to newer version, and it worked!

I had some problems, so I tried to remove NodeJS (I had the same problem like this guy: https://github.com/nodesource/distributions/issues/1157).

And installed LTS version: https://askubuntu.com/questions/1265813/how-to-update-node-js-to-the-long-term-support-version-on-ubuntu-20-04.

Now I have:

node -v v16.16.0

and script works! Thank you :)

const id = new Crypto().randomUUID();

本文标签: JavaScriptNodeJScryptorandomUUID is not a functionStack Overflow