Skip to content

Instantly share code, notes, and snippets.

@kbjr
Created July 28, 2019 04:33
Show Gist options
  • Save kbjr/23632196cd7ea4818e9f12c3b209d5a2 to your computer and use it in GitHub Desktop.
Save kbjr/23632196cd7ea4818e9f12c3b209d5a2 to your computer and use it in GitHub Desktop.
import { randomBytes } from 'crypto';
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
const randomString = (length) => {
return new Promise((resolve, reject) => {
const chars = new Array(length);
randomBytes(length, (error, bytes) => {
if (error) {
return reject(error);
}
for (let i = 0; i < length; i++) {
chars[i] = charset[bytes[i] % charset.length];
}
resolve(chars.join(''));
});
});
};
@kbjr
Copy link
Author

kbjr commented Jul 28, 2019

To use:

import { randomString } from './random-string';

// Get a random, 8 character ID
randomString(8);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment