@react-native-module/randombytes
Version:
implementation of randomBytes for React Native
42 lines (38 loc) • 1.31 kB
JavaScript
;
var buffer = require('buffer');
var randomBytesWithoutNativeModule = require('./randomBytesWithoutNativeModule.js');
function randomBytes(size, callback) {
try {
const RNRandomBytes = require('react-native').NativeModules.RNRandomBytes;
if (!callback) {
return RNRandomBytes.randomBytesSync(size);
}
RNRandomBytes.randomBytes(size, (err, base64String) => {
if (err != null) {
callback(err, null);
}
else {
callback(null, buffer.Buffer.from(base64String, 'base64'));
}
});
}
catch (error) {
if (error) {
if (['randomBytesSync', 'randomBytes'].some(v => error.message.includes(`Cannot read property '${v}' of null`))) {
if (callback != null) {
return randomBytesWithoutNativeModule.randomBytesWithoutNativeModule(size, callback);
}
else {
return randomBytesWithoutNativeModule.randomBytesWithoutNativeModule(size);
}
}
}
if (callback) {
callback(error, null);
}
else {
throw error;
}
}
}
module.exports = randomBytes;