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,
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.
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'))
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.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With