The equivalent to os.urandom
is found in the crypto module: crypto.randomBytes
. That module also contains most other functions you might want for password hashing etc.
To use the same password character set as your current code, you could do
exports.gen = (length = 10) ->
throw new Error 'Length is not a number!' if typeof length isnt 'number'
throw new Error 'Length must be [10..128]' unless 10 <= length <= 128
range = 126 - 33
buffer = require('crypto').randomBytes length # note: may throw an error
(String.fromCharCode(33 + (range * c / 255) | 0) for c in buffer).join ''
I've changed a few small things
length
instead of n
- Slightly more descriptive error messages, i.e. what is not a number, and sterner wording for bad length values ("prefered" [sic] makes it sound as though it's just a suggestion, but it's actually a requirement)
- CoffeeScript has chained comparisons like Python, so
10 <= length <= 128
can be used