Convert nodejs' Buffer to browsers' javascript

前端 未结 3 828
耶瑟儿~
耶瑟儿~ 2020-12-10 11:04

I\'m converting my code from Node.js to browsers\' javascript, but I have a problem with the Buffers in node.js. How can I use them in Javascript?

Here\'s an example

相关标签:
3条回答
  • 2020-12-10 11:46

    To convert back to the string, use the buffer's toString method with a supplied encoding.

    http://nodejs.org/docs/latest/api/buffers.html#buffer.toString

    var buffer = new Buffer("foo", "utf8");
    var str = buffer.toString("utf8");
    str === "foo";
    
    0 讨论(0)
  • 2020-12-10 11:55

    With https://github.com/substack/node-browserify you can work with buffers in the Browser by using: https://github.com/toots/buffer-browserify. However: this can be very slow in the browser: For faster access use https://github.com/chrisdickinson/bops

    0 讨论(0)
  • 2020-12-10 11:55

    There is no direct support for Buffer in browser-based JavaScript, and I am not aware of any compatibility library that implements the Buffer API (yet).

    The equivalent functionality in the browser is provided by TypedArrays. You can learn about them here:

    • https://developer.mozilla.org/en/JavaScript_typed_arrays

    When porting a Node Buffer-based implementation to browser-based JavaScript, I found these answers helpful:

    • Converting between strings and ArrayBuffers
    • Javascript - Converting between Unicode string and ArrayBuffer
    0 讨论(0)
提交回复
热议问题