Can we use process.hrtime() as UUID in node.js?

房东的猫 提交于 2020-01-25 05:00:06

问题


Can we use process.hrtime() as universal unique id within the current process ?

var uuid = parseInt(process.hrtime().join(''));

回答1:


You can use process.hrtime() to create identifiers with low chance of collision, but they are not unique, especially not across application restarts (which matters if you persist any of them to a database or similar), and not when several threads/processes/instances are involved.

From the documentation:

These times are relative to an arbitrary time in the past, and not related to the time of day

Also, by using parseInt(....join('')), you are introducing a second way for collisions to happen: e.g. [1, 23] and [12, 3] will lead to the same result.

If you want to build your own solution (a[0] * 1e9 + a[1] comes to mind as a naive approach), you should also be aware of the precision limits of JavaScript numbers -- there's a reason why hrtime() returns a tuple and not just a single number. When in doubt, when you need proper UUIDs, you should probably use proper UUIDs ;-)




回答2:


This question is rather old, but I managed to figure out something that works like this (partially, on a single machine, and NOT completely validated yet). See Is this a viable, monotonically increasing timeId in javascript?. (Note, requires Node 10 or 11, and I've only validated on Mac OS Mojave so far)

That solution will not provide a UUID, but it should produce an ID that is always increasing in value. Some other machine/process ID would have to be appended to it to make it really unique.



来源:https://stackoverflow.com/questions/49708974/can-we-use-process-hrtime-as-uuid-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!