raphaelrk
raphaelrk

Reputation: 827

Equivalent to python's uuid.uuid4().hex in javascript?

Python has functionality to create hex UUID's like so:

>>> import uuid
>>> uuid.uuid4().hex
'47be94c37e484e13ab04ed3c54a5b681'

A solution idea is to just generate each of the 32 characters randomly on the frontend, but I don't know if there's anything special about the hex UUID's, and I'm also not sure if there's a good way to validate the client sent back a valid value (and not a series of 32 a's)

Edit: just realized there's nothing special about the "hex" formatting, it's just missing the dashes. Will leave that bullet up in case it confuses anyone else.

Upvotes: 6

Views: 8320

Answers (1)

roarky
roarky

Reputation: 158

You can use buffer to convert to hex conveniently.

const uuid = require('uuid')
const buffer = Buffer.alloc(16);

uuid.v4({}, buffer);
console.log(buffer.toString('hex'));

Not the cleanest and most elegant solution but will get the job done.

Upvotes: 3

Related Questions