The example from Bohdan Yurchuk is incorrect, unfortunately I do not have enough reputation to point it out in a comment.
.substring()
takes startIndex
and endIndex
parameters not startIndex
and count
.
Correct code
function generateUuidBySeed(seedString) {
const hash = crypto.createHash('sha256').update(seedString).digest('hex');
// UUID version 4 consists of 32 hexadecimal digits in the form:
// 8-4-4-4-12 (total 36 characters including hyphens)
console.log(hash)
const uuid = [
hash.substring(0, 8),
hash.substring(8, 12),
'4' + hash.substring(12, 15), // Set the version to 4
'8' + hash.substring(15, 18), // Set the variant to 8 (RFC 4122)
hash.substring(18, 30),
].join('-');
return uuid;
}
// Example usage:
const seedString = 'your-seed-string';
const uuid = generateUuidBySeed(seedString);
console.log(uuid);
crypto
is a native Node.js module and does not require additional libraries.