Created
October 2, 2019 15:03
-
-
Save saibotsivad/a5c21c2cfbfae32aed5e880c798fa01a to your computer and use it in GitHub Desktop.
generate id in nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { randomBytes } = require('crypto') | |
const ID_LENGTH = 64 | |
const escape = string => string | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
.replace(/=/g, '') | |
module.exports = async () => new Promise((resolve, reject) => { | |
randomBytes(ID_LENGTH, (error, bytes) => { | |
if (error) { | |
reject(error) | |
} else { | |
const [ seconds, nanoseconds ] = process.hrtime() | |
resolve(escape( | |
crypto | |
.createHash('sha512') | |
.update(`${bytes.toString('base64')}${seconds}${nanoseconds}`) | |
.digest('base64') | |
)) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment