admin管理员组文章数量:1194548
I'm very new to JS, I want to generate an UUID. Here's what I tried, step by step:
mkdir test
cd test
touch file1.js
- 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:
mkdir test
cd test
touch file1.js
- 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
4 Answers
Reset to default 18here 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
版权声明:本文标题:javascript - NodeJS, crypto.randomUUID is not a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737573827a1997186.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
try
/catch
should be inside thetry
, since if crypto support is disabled,crypto
will beundefined
where you're trying to use it.) – T.J. Crowder Commented Aug 2, 2022 at 9:32randomUUID
function was added inNode v15.6.0
. You need to upgrade node. – mousetail 'he-him' Commented Aug 2, 2022 at 9:36