UNPKG

608 BJavaScriptView Raw
1var crypto = require('crypto')
2
3if (crypto.randomFillSync) {
4 // We reuse buffers with the same size to avoid memory fragmentations
5 // for better performance
6 var buffers = { }
7 module.exports = function (bytes) {
8 var buffer = buffers[bytes]
9 if (!buffer) {
10 // `Buffer.allocUnsafe()` faster because it don’t clean memory.
11 // We do not need it, since we will fill memory with new bytes anyway.
12 buffer = Buffer.allocUnsafe(bytes)
13 if (bytes <= 255) buffers[bytes] = buffer
14 }
15 return crypto.randomFillSync(buffer)
16 }
17} else {
18 module.exports = crypto.randomBytes
19}