Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffer not found in Node.JS browser code

I want to use a node.js function on the browser with browserify. In my code, there is a line as follows:

var x = new Buffer('abc..', 'hex')

However, this causes an error ReferenceError: Buffer is not defined. I tried to install [buffer-browserify][1] and include it like this:

var Buffer = require('buffer');

but now I get the error Error: Cannot find module 'buffer'..

so -how- can I use the Buffer class in browser javascript?

Thanks for any help,

Update:

In order to build it with browserify, I created an input.js file as follows:

var Buffer = require('buffer');
console.log(Buffer);

and I tried to build it with browserify input.js -o output.js and I included output.js in my browser code, it prints the Buffer variable. However, I still get the same error (ReferenceError: Buffer is not defined) when I try to use it.

like image 793
jeff Avatar asked Dec 17 '16 12:12

jeff


1 Answers

This is understandably confusing, but here's how to make it work, with some explanatory bullets.

1) Create your source javascript file

// app.js file
var privateKey = new Buffer('abcdef00', 'hex')
console.log(privateKey.toString('hex'))
  • Not you do not need a require('Buffer') call here. Browserify will make some of the node.js core globals available automatically. Since Buffer is a global in npm (meaning you don't have to call require to use it), you can just use it directly.
  • This will print the key to the console

2) Browserify it from the command line

npm install --save browserify
$(npm bin)/browserify app.js > app-browser.js

3) Reference app-browser.js from an HTML file

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Browserify buffer</title>
</head>
<body>
<h1>Browserify Buffer</h1>
<script src="app-browser.js">
</script>
</body>
</html>
like image 69
Peter Lyons Avatar answered Oct 31 '22 03:10

Peter Lyons