Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate base62 UUIDs in node.js?

I'm looking for a solution to generate base62 UUIDs in node.js. I'd like to avoid base64 as I intend to create folders based on these UUIDs and characters like =, \, -, _ (as in some implementations) are not that human/filesystem friendly.

Base62 also has the advantage (in my context) of being shorter than a typical v4 UUID.

UPDATE (for clarity): I should have said earlier that I already tried using base62 module but this doesn't solve my issue since base62 takes numbers in javascript integer numbers are only precise up to 52 bits while UUIDs have 128.

like image 661
Dário Avatar asked Dec 20 '22 03:12

Dário


2 Answers

Here is a comprehensive answer:

Solution A: base-x + node-uuid

Inspired by @Jonathan's earlier comment.

Use node-uuid to generate the UUID and then encode it with base-x:

var buf = new Buffer(16);
var uuid = Uuid.v4(null, buf);
var uuidB62 = baseX.encode(uuid);
// -> 71jbvv7LfRKYp19gtRLtkn

base-x is very fast so this is the most performant solution.

Solution B: uuid-base62

Before knowing about base-x I went ahead and created a module for the base62 encoding (b62) and another for the base62 UUID generation: uuid-base62:

var uuidB62 = uuidBase62.v4();  // -> 2qY9COoAhfMrsH7mCyh86T

This is the no frills solution. Currently it's not as fast as A since b62 is much slower but I intend to replace it with base-x.

UPDATE: uuid-base62 has been updated to use base-x.

like image 67
Dário Avatar answered Dec 21 '22 17:12

Dário


UPDATE: The module I originally pointed out is for converting base 62 numbers to base 10 and vice versa, so that won't do. Looks like original poster is creating their own module to do this: https://github.com/dmarcelino/b62

There is a base62 module that you can use. Here is their sample code:

Base62 = require('base62')
Base62.encode(999)  // 'g7' 
Base62.decode('g7') // 999

The module can be installed with npm install base62. To have it as a dependency in your package.json, use npm install --save base62 instead.

like image 35
Trott Avatar answered Dec 21 '22 18:12

Trott