Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  132] [ 5]  / answers: 1 / hits: 34831  / 8 Years ago, sat, december 17, 2016, 12:00:00

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.


More From » node.js

 Answers
9

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>

[#59672] Wednesday, December 14, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rossthomasn

Total Points: 122
Total Questions: 78
Total Answers: 105

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
rossthomasn questions
Wed, Mar 16, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Thu, Nov 26, 20, 00:00, 4 Years ago
Sun, May 31, 20, 00:00, 4 Years ago
;