Reputation: 131
Currently trying to generate a random buffer of size x in javascript/node/typescript, seems like the most common way to do this is using the crypto
library
However, I'm having compilation issues with this library, as I'm using a bundler for a browser extension. Gives me the following error Failed to resolve 'stream' from '/Users/moizahmed/Documents/node\_modules/cipher-base/index.js'
I'm also only using one function from the crypto library, the randomBytes
function, and was wondering if I could do this all without the use of a library?
Seems pretty trivial in other languages, not sure how to get this in javascript without the crypto library
Upvotes: 0
Views: 2077
Reputation: 131
Here's a potential work around which I've currently implemented
const randomBytes = () => {
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(4, '0123456789abcdefghijklmnopqrstuvwxyz');
const buf1 = Buffer.from(rString, 'hex');
return buf1
}
Seems to get the job done, but curious as to whether there's better solutions
Upvotes: 1