crypto.randomuuid不是函数

问题描述 投票:0回答:3

mkdir test

  1. cd test
  2. touch file1.js
  3. inside
    file1.js

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


您会看到错误。怎么了?我在任何地方都找不到答案。节点JS版本:

node -v

显示

v12.22.9

enter image description here 在这里您可以使用

randomBytes()
javascript node.js uuid
3个回答
18
投票

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

您还可以使用UUIDV4而不是加密v4
const { uuid } = require('uuidv4'); console.log(uuid());


错误是添加了节点版本的

crypto.randomUUID
函数。
根据官方文档:
Https://nodejs.org/api/crypto.html#cryptorandomuuidoptions

10
投票

因此,如果您不想使用较新的节点版本,则可能是您的最佳选择是使用

Https://www.npmjs.com/package/uuid
    

I升级为新版本,它起作用了! 我有一些问题,所以我尝试删除nodejs(我遇到了像这个人一样的问题:https://github.com/nodesource/distributions/issues/1157

)。

并安装了LTS版本:Https://askubuntu.com/questions/1265813/how-to-update-node-node-js-to-the-the-long-term-term-term-support-version-version-on-ubuntu-20-04,

现在我有:

3
投票

> v14.17.0

node -v

脚本有效!谢谢:)

遇到这个问题的人,请尝试以以下方式导入此问题:

v16.16.0


import * as crypto from 'node:crypto';

var id = crypto.randomUUID() ......

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.