UNPKG

@react-native-module/randombytes

Version:
40 lines (37 loc) 1.24 kB
import { Buffer } from 'buffer'; import { randomBytesWithoutNativeModule } from './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.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(size, callback); } else { return randomBytesWithoutNativeModule(size); } } } if (callback) { callback(error, null); } else { throw error; } } } export { randomBytes as default };