ksuid
A Node.js implementation of Segment's KSUID library.
You may also be interested in ksuid-cli
.
Installation
$ npm install ksuid
Usage
Require the module:
const KSUID = require('ksuid')
Creation
You can create a new instance synchronously:
const ksuidFromSync = KSUID.randomSync()
Or asynchronously:
const ksuidFromAsync = await KSUID.random()
You can also specify a specific time, either in milliseconds or as a Date
object:
const ksuidFromDate = KSUID.randomSync(new Date("2014-05-25T16:53:20Z"))
const ksuidFromMillisecondsAsync = await KSUID.random(1401036800000)
Or you can compose it using a timestamp and a 16-byte payload:
const crypto = require('crypto')
const yesterdayInMs = Date.now() - 86400 * 1000
const payload = crypto.randomBytes(16)
const yesterdayKSUID = KSUID.fromParts(yesterdayInMs, payload)
You can parse a valid string-encoded KSUID:
const maxKsuid = KSUID.parse('aWgEPTl1tmebfsQzFP4bxwgy80V')
Finally, you can create a KSUID from a 20-byte buffer:
const fromBuffer = new KSUID(buffer)
Properties
Once the KSUID has been created, use it:
ksuidFromSync.string
ksuidFromSync.raw
ksuidFromSync.date
ksuidFromSync.timestamp
ksuidFromSync.payload
Comparisons
You can compare KSUIDs:
todayKSUID.compare(yesterdayKSUID)
todayKSUID.compare(todayKSUID)
yesterdayKSUID.compare(todayKSUID)
And check for equality:
todayKSUID.equals(todayKSUID)
todayKSUID.equals(yesterdayKSUID)
Validation
You can check whether a particular buffer is a valid KSUID:
KSUID.isValid(buffer)