我找到了这个答案有没有办法根据JDK或某些库中的种子字符串生成相同的UUID?但这是java方式。
我需要同样的,但在 javascript 中,我可以使用任何 npm 模块或任何库或自定义函数。
您可以通过这种方式使用 UUID 来为您的输入获取始终相同的 UUID 字符串:
字符串aString =“JUST_A_TEST_STRING”;
字符串结果 = UUID.nameUUIDFromBytes(aString.getBytes()).toString();
当前接受的解决方案仅适用于 uuid-1345 的 github 页面的 NodeJS 环境:
非功能:
- 由于使用了 NodeJS 的加密模块,因此无法在浏览器中工作。
如果您正在寻找可在浏览器中运行的解决方案,您应该使用更流行的 uuid 库。
const uuidv5 = require('uuid/v5');
// ... using a custom namespace
//
// Note: Custom namespaces should be a UUID string specific to your application!
// E.g. the one here was generated using this modules `uuid` CLI.
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
只要您传递相同的命名空间,UUID 将保持一致。
希望有帮助。
最简单的方法:
const getUuid = require('uuid-by-string')
const uuidHash = getUuid('Hello world!')
// d3486ae9-136e-5856-bc42-212385ea7970
终于这来救我了
var UUID = require('uuid-1345');
UUID.v5({
namespace: UUID.namespace.url,
name: "test"
});
这是工作示例:
const crypto = require('crypto');
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)
const uuid = [
hash.substr(0, 8),
hash.substr(8, 4),
'4' + hash.substr(12, 3), // Set the version to 4
'8' + hash.substr(15, 3), // Set the variant to 8 (RFC 4122)
hash.substr(18, 12),
].join('-');
return uuid;
}
// Example usage:
const seedString = 'your-seed-string';
const uuid = generateUuidBySeed(seedString);
console.log(uuid, '===>', '4400db7b-baad-4821-890a-93f9d14c358f');