Skip to content

Instantly share code, notes, and snippets.

@bausmeier
Last active Feb 19, 2016
Embed
What would you like to do?

Non-standard UUID generator

The UUIDs are 128 bits and are represented as 32 character hex strings. The first 14 hex characters are the number of microseconds since the Unix epoch, and the remaining 18 hex characters are random.

Usage

const utcr = require('utc-random');

// Call it directly
utcr((err, id) => {
  if (err) throw err;
  console.log(id);
});

// Or call the generate function
utcr.generate((err, id) => {
  if (err) throw err;
  console.log(id);
});
'use strict';
const crypto = require('crypto');
const microtime = require('microtime');
/**
* Generate a 128 bit UUID.
*
* The first 14 hex characters are the number of microseconds since the Unix epoch.
* The remaining 18 hex characters are random.
*/
function generate(callback) {
// Create the date buffer
const dateBuffer = new Buffer(7);
dateBuffer.writeUIntBE(microtime.now(), 0, 7);
// Create the random buffer
crypto.randomBytes(9, (err, randomBuffer) => {
if (err) {
return callback(err);
}
// Concat and return the result
const buffer = Buffer.concat([dateBuffer, randomBuffer], 16);
return callback(null, buffer.toString('hex'));
});
}
module.exports = exports = generate;
exports.generate = generate;
{
"name": "utc-random",
"description": "Non-standard UUID generator",
"version": "1.0.1",
"main": "index.js",
"repository": "gist:05632a6eba6de810f474",
"license": "WTFPL",
"dependencies": {
"microtime": "~2.0.0"
},
"engines": {
"node": ">=4.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment