@jbcampbell/ksuid
TypeScript icon, indicating that this package has built-in type declarations

2.4.0 • Public • Published

ksuid

A Node.js implementation of Segment's KSUID library. Supports Node.js 6, 8 and 10.

You may also be interested in ksuid-cli.

Installation

$ npm install ksuid

Usage

Require the module:

const KSUID = require('ksuid')

Or, using TypeScript:

import KSUID = require('ksuid')

Creation

You can create a new instance synchronously:

const ksuidFromSync = KSUID.randomSync()

Or asynchronously:

const ksuidFromAsync = await KSUID.random()

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 // The KSUID encoded as a fixed-length string
ksuidFromSync.raw // The KSUID as a 20-byte buffer
ksuidFromSync.date // The timestamp portion of the KSUID, as a `Date` object
ksuidFromSync.timestamp // The raw timestamp portion of the KSUID, as a number
ksuidFromSync.payload // A Buffer containing the 16-byte payload of the KSUID (typically a random value)

Comparisons

You can compare KSUIDs:

todayKSUID.compare(yesterdayKSUID) // 1
todayKSUID.compare(todayKSUID) // 0
yesterdayKSUID.compare(todayKSUID) // -1

And check for equality:

todayKSUID.equals(todayKSUID) // true
todayKSUID.equals(yesterdayKSUID) // false

Validation

You can check whether a particular buffer is a valid KSUID:

KSUID.isValid(buffer) // Boolean

Readme

Keywords

Package Sidebar

Install

npm i @jbcampbell/ksuid

Weekly Downloads

7

Version

2.4.0

License

MIT

Unpacked Size

11.4 kB

Total Files

6

Last publish

Collaborators

  • jbcampbell