Skip to content

Instantly share code, notes, and snippets.

@saibotsivad
Created October 2, 2019 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saibotsivad/a5c21c2cfbfae32aed5e880c798fa01a to your computer and use it in GitHub Desktop.
Save saibotsivad/a5c21c2cfbfae32aed5e880c798fa01a to your computer and use it in GitHub Desktop.
generate id in nodejs
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