title: Secure random token in Node.js
body: <p>In <a href="https://stackoverflow.com/questions/8838624/nodejs-send-email-on-registration/8842959#8842959">this question</a> Erik needs to generate a secure random token in Node.js. There's the method <code>crypto.randomBytes</code> that generates a random Buffer. However, the base64 encoding in node is not url-safe, it includes <code>/</code> and <code>+</code> instead of <code>-</code> and <code>_</code>. Therefore, the easiest way to generate such token I've found is</p>
  
  <pre><code>require('crypto').randomBytes(48, function(ex, buf) {
      token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
  });
  </code></pre>
  
  <p>Is there a more elegant way?</p>