Bri*_*own 21 javascript uuid node.js
我对 JS 很陌生,我想生成一个 UUID。这是我一步一步尝试的:
mkdir testcd testtouch file1.jsfile1.js:let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
var uuid = crypto.randomUUID();
console.log(uuid);Run Code Online (Sandbox Code Playgroud)
你会看到错误。怎么了?我在任何地方都找不到答案。节点 JS 版本:
node -v节目v12.22.9
小智 18
在这里你可以使用randomBytes()方法来获取唯一的ID
const crypto = require('crypto');
console.log(crypto.randomBytes(20).toString('hex'));
Run Code Online (Sandbox Code Playgroud)
您还可以使用 uuidv4 代替 crypto
const { uuid } = require('uuidv4');
console.log(uuid());
Run Code Online (Sandbox Code Playgroud)
小智 9
错误是该crypto.randomUUID功能是为 Node 版本添加的> v14.17.0。
这是根据官方文档:https ://nodejs.org/api/crypto.html#cryptorandomuuidoptions
因此,如果您不想使用较新的 Node 版本,您最好的选择可能是使用https://www.npmjs.com/package/uuid