简体   繁体   中英

How can I use node.js buffer library in client side javascript

I would like to use buffer library (in order handle binary data) in my website. here is my use case:

const privateKey = Buffer.from('<User's private key here>', 'hex');

buffer works fine in node.js without any additional npm module or script. but somehow,it is not working in web browser.it is showing an error

uncaught refernce error: buffer is not defined

I though we need to add library script file in our html file. please help me to fix this?

Add standalone script to HTML from https://github.com/feross/buffer

    <script src="https://bundle.run/buffer@6.0.3"></script>

Then in JS

const privateKey = buffer.Buffer.from(PRIVATE_KEY_1, "hex");

The buffer object is not available outside of Node.js, ie in the browser. This is because (in case you were not aware) Node.js is a javascript runtime, therefore Node.js specific functionalities do not exist within a browser environment, because they are associated with the V8 engine, but not the V8 engine within a browser (note the difference here).

So essentially, uncaught refernce error: buffer is not defined means that this this doesn't exist in the browser.

https://nodejs.org/api/buffer.html#buffer_new_buffer_array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM