ajsie ajsie - 3 months ago 43
Javascript Question

How to generate random SHA1 hash to use as ID in node.js?

I am using this line to generate a sha1 id for node.js:

crypto.createHash('sha1').digest('hex');


The problem is that it's returning the same id every time.

Is it possible to have it generate a random id each time so I can use it as a database document id?

Answer

Have a look here: How do I use node.js Crypto to create a HMAC-SHA1 hash? I'd create a hash of the current timestamp + a random number to ensure hash uniqueness:

var current_date = (new Date()).valueOf().toString();
var random = Math.random().toString();
crypto.createHash('sha1').update(current_date + random).digest('hex');