Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't find variable: Buffer

I'm trying to use node modules in my react-native app, and I'm taking the ReactNativify approach here.

I'm all set up now, and I got the crypto package to load in fine. However when I added in eth-lightwallet things have been getting weird.

Every since I added that package in, npm hasn't been installing dependancies of anything. Meaning I've had to add them in manually. And everytime I install a dependency somehow related to eth-lightwallet, that module is uninstalled. Although tedious and annoying, I'm hoping it can shed light onto my current problem.

Right now I'm running into a Can't find variable: Buffer which is being thrown in a util folder in the standard library. I've taken a look at the code and it's accessing Buffer from a global namespace. Thing is, I'm importing Buffer into the global namespace. Here's a look at my global.js

// Inject node globals into React Native global scope.
global.Buffer = require('buffer').Buffer;
global.process = require('process');
global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production';

// Needed so that 'stream-http' chooses the right default protocol.
global.location = {
    protocol: 'file:',
};

// Don't do this in production. You're going to want to patch in
// https://github.com/mvayngrib/react-native-randombytes or similar.
global.crypto = {
    getRandomValues(byteArray) {
        for (let i = 0; i < byteArray.length; i++) {
            byteArray[i] = Math.floor(256 * Math.random());
        }
    },
};

My guess is the standard library is being evaluated before this global is being loaded in, and thus the error is thrown.

like image 498
arshbot Avatar asked Jan 24 '18 22:01

arshbot


2 Answers

In TypeScript I had to import Buffer explicitly.

import { Buffer } from "buffer";

I would have expected that the compiler would complain about Buffer being missing before the import and/or that "source.organizeImports": true would have removed the line when saving the file, but neither were true.

@ehacinom's solution also worked.

like image 145
Jan Aagaard Avatar answered Sep 20 '22 22:09

Jan Aagaard


I ran npm install buffer and put this at the top of files that needed Buffer:

global.Buffer = global.Buffer || require('buffer').Buffer
like image 22
ehacinom Avatar answered Sep 21 '22 22:09

ehacinom