I'm sure you will find this helpful: http://jsdo.it/tsmallfield/uint8array.

Click on javascript tab. There will appear the code to convert the Uint8Array in a string. The author shows 2 method:

  • The first is about creating a view.
  • The second offsetting bytes.

EDIT: report the code for completeness

var buffer = new ArrayBuffer( res.length ), // res is this.response in your case
    view   = new Uint8Array( buffer ),
    len    = view.length,
    fromCharCode = String.fromCharCode,
    i, s, str;    

/**
 *  1) 8bitの配列に入れて上位ビットけずる
 */
str = "";

for ( i = len; i--; ) {
  view[i] = res[i].charCodeAt(0);
}

for ( i = 0; i < len; ++i ) {
  str += fromCharCode( view[i] );
}    

/**
 *  2) & 0xff で上位ビットけずる
 */
str = "";

for ( i = 0; i < len; ++i ) {
  str += fromCharCode( res[i].charCodeAt(0) & 0xff );
}
Answer from user278064 on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › ArrayBuffer
ArrayBuffer - JavaScript - MDN Web Docs
You cannot directly manipulate ... specific format, and use that to read and write the contents of the buffer. The ArrayBuffer() constructor creates a new ArrayBuffer of the given length in bytes....
Discussions

How can I convert []byte to ArrayBuffer
I have some js returned ArrayBuffer object, and I want to use golang to process it as []byte. But I don't know how to do it. I did not find the document about it. More on github.com
🌐 github.com
4
January 26, 2015
node.js - nodejs conversion from buffer data to byte array - Stack Overflow
For example, while ArrayBuffer#slice() creates a copy of the slice, the implementation of Buffer#slice() creates a view over the existing Buffer without copying, making Buffer#slice() far more efficient. It is also possible to create new TypedArray instances from a Buffer with the following caveats: The Buffer object's memory is copied to the TypedArray, not shared. The Buffer object's memory is interpreted as an array of distinct elements, and not as a byte ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Converting byte[] to ArrayBuffer in Nashorn - Stack Overflow
How do I convert an array of bytes into ArrayBuffer in Nashorn? I am trying to insert binary data into a pure JavaScript environment (i.e., it doesn't have access to Java.from or Java.to) and so wo... More on stackoverflow.com
🌐 stackoverflow.com
node.js - Convert a binary NodeJS Buffer to JavaScript ArrayBuffer - Stack Overflow
How can I convert a NodeJS binary buffer into a JavaScript ArrayBuffer? ... a good example would be writing a library that worked with File's in browsers and also for NodeJS files? ... Another reason is that a float takes too many bytes of RAM when stored in an Array. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 575282 › javascript-readasarraybuffer-to-bytes-and-pass-it
JavaScript readAsArrayBuffer to bytes and pass it to MVC controller - Microsoft Q&A
Hi @AzureDevUser , As far as I think,you could convert to base64 string using the javascript.And then you could use ajax to post the parameter to the controller.Just like this: 137300-new-text-document-2.txt Best regards, Yijing Sun
🌐
Bun
bun.com › binary data › convert a uint8array to an arraybuffer
Convert a Uint8Array to an ArrayBuffer - Bun
1 week ago - A Uint8Array is a typed array, a view over data in an underlying ArrayBuffer. The buffer property returns that ArrayBuffer. const arr = new Uint8Array(64); arr.buffer; // => ArrayBuffer(64) The Uint8Array may be a view over a subset of the data in the underlying ArrayBuffer. In this case, the buffer property returns the entire buffer, and the byteOffset ...
🌐
JavaScript.info
javascript.info › tutorial › binary data, files
ArrayBuffer, binary arrays
July 11, 2022 - If an ArrayBuffer argument is supplied, the view is created over it. We used that syntax already. Optionally we can provide byteOffset to start from (0 by default) and the length (till the end of the buffer by default), then the view will cover only a part of the buffer. If an Array, or any array-like object is given, it creates a typed array of the same length and copies the content.
🌐
Telerik
telerik.com › blogs › array-buffers-javascript
Array Buffers in JavaScript
October 22, 2025 - In this article, we look at Array Buffers and how they are used to handle raw binary data in JavaScript.
🌐
Chrome Developers
developer.chrome.com › blog › how to convert arraybuffer to and from string
How to convert ArrayBuffer to and from String | Blog | Chrome for Developers
June 14, 2012 - For example, if you know that the bytes in an ArrayBuffer represent an array of 16-bit unsigned integers, you just wrap the ArrayBuffer in a Uint16Array view and you can manipulate its elements using the brackets syntax as if the Uint16Array was an integer array:
🌐
GitHub
github.com › gopherjs › gopherjs › issues › 165
How can I convert []byte to ArrayBuffer · Issue #165 · gopherjs/gopherjs
January 26, 2015 - I have some js returned ArrayBuffer object, and I want to use golang to process it as []byte. But I don't know how to do it. I did not find the document about it.
Author   gopherjs
Find elsewhere
🌐
Medium
medium.com › @diptab11 › arraybuffer-in-javascript-a-deep-dive-into-binary-data-handling-part-2-e97862df799a
ArrayBuffer in JavaScript: A Deep Dive into Binary Data Handling (Part 2) | by Dipta Barua | Medium
February 13, 2025 - A Uint8Array is used to view the buffer as an array of bytes. This approach is useful for tasks like image processing, file validation, or custom file parsing. When sending or receiving data over the network, binary data is often more efficient than text-based formats like JSON. ArrayBuffer is commonly used in APIs like Fetch and WebSockets to handle binary data. fetch('https://example.com/data.bin') .then(response => response.arrayBuffer()) // Convert the response to an ArrayBuffer .then(buffer => { const data = new Uint8Array(buffer); // View the buffer as bytes console.log(data); // Log the binary data });
🌐
Bobby Hadz
bobbyhadz.com › blog › convert-blob-to-arraybuffer-in-javascript
How to convert a Blob to an ArrayBuffer in JavaScript | bobbyhadz
April 4, 2024 - The method returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. The byteLength property of the ArrayBuffer returns the length of the ArrayBuffer in bytes.
🌐
Kotlinlang
slack-chats.kotlinlang.org › t › 14150421 › hi-everyone-i-want-to-convert-arraybuffer-to-byte-array-can-
Hi everyone I want to convert arraybuffer to byte array can kotlinlang #javascript
val fileReader = FileReader() fileReader.readAsArrayBuffer(Blob(_arrayOf_(file))) var fileByteArray = ByteArray(file.size.toInt()) val arrayBuffer = fileReader.result as ArrayBuffer next step is to convert arrayBuffer to byte array in kotlin/js???
Top answer
1 of 2
24

The Buffer docs are very enlightening:

Prior to the introduction of TypedArray, the JavaScript language had no mechanism for reading or manipulating streams of binary data. The Buffer class was introduced as part of the Node.js API to enable interaction with octet streams in TCP streams, file system operations, and other contexts.

With TypedArray now available, the Buffer class implements the Uint8Array API in a manner that is more optimized and suitable for Node.js.

Buffer instances are also Uint8Array instances. However, there are subtle incompatibilities with TypedArray. For example, while ArrayBuffer#slice() creates a copy of the slice, the implementation of Buffer#slice() creates a view over the existing Buffer without copying, making Buffer#slice() far more efficient.

It is also possible to create new TypedArray instances from a Buffer with the following caveats:

  1. The Buffer object's memory is copied to the TypedArray, not shared.

  2. The Buffer object's memory is interpreted as an array of distinct elements, and not as a byte array of the target type. That is, new Uint32Array(Buffer.from([1, 2, 3, 4])) creates a 4-element Uint32Array with elements [1, 2, 3, 4], not a Uint32Array with a single element [0x1020304] or [0x4030201].

They go on to mention TypedArray.from, which in node accepts Buffers, so the 'correct' way is:

var arrByte = Uint8Array.from(data)

...however, this shouldn't be necessary at all since a Buffer is a Uint8Array and new UintArray(someBuffer) does work just fine.

There's also no context in your question, but Blob doesn't exist in node, and you shouldn't need it anyway, since Buffer already gives you raw access to binary data and the other fs methods let you read and write files.

2 of 2
10
  import * as fs from 'fs';
  [...]
  event:(data) => {
    fs.readFile(data, function(err, data) {
      var arrByte= new Uint8Array.from(Buffer.from(data))
      var binaryData= new Blob([arrByte])
      if (err) throw err;
      console.log(binaryData)
    }
 }
Top answer
1 of 16
352

Update 2016 - five years on there are now new methods in the specs (see support below) to convert between strings and typed arrays using proper encoding.

##TextEncoder

The TextEncoder represents:

The TextEncoder interface represents an encoder for a specific method, that is a specific character encoding, liarraybufferke utf-8, iso-8859-2, koi8, cp1261, gbk, ... An encoder takes a stream of code points as input and emits a stream of bytes.

Change note since the above was written: (ibid.)

Note: Firefox, Chrome and Opera used to have support for encoding types other than utf-8 (such as utf-16, iso-8859-2, koi8, cp1261, and gbk). As of Firefox 48 [...], Chrome 54 [...] and Opera 41, no other encoding types are available other than utf-8, in order to match the spec.*

*) Updated specs (W3) and here (whatwg).

After creating an instance of the TextEncoder it will take a string and encode it using a given encoding parameter:

if (!("TextEncoder" in window)) 
  alert("Sorry, this browser does not support TextEncoder...");

var enc = new TextEncoder(); // always utf-8
console.log(enc.encode("This is a a string to be converted to a Uint8Array"));

You then of course use the .buffer parameter on the resulting Uint8Array to convert the underlaying ArrayBuffer to a different view if needed.

Just make sure that the characters in the string adhere to the encoding schema, for example, if you use characters outside the UTF-8 range in the example they will be encoded to two bytes instead of one.

For general use you would use UTF-16 encoding for things like localStorage.

##TextDecoder

Likewise, the opposite process uses the TextDecoder:

The TextDecoder interface represents a decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, ... A decoder takes a stream of bytes as input and emits a stream of code points.

All available decoding types can be found here.

if (!("TextDecoder" in window))
  alert("Sorry, this browser does not support TextDecoder...");

var enc = new TextDecoder("utf-8");
var arr = new Uint8Array([84,104,105,115,32,105,115,32,97,32,85,105,110,116,
                          56,65,114,114,97,121,32,99,111,110,118,101,114,116,
                          101,100,32,116,111,32,97,32,115,116,114,105,110,103]);
console.log(enc.decode(arr));

##The MDN StringView library

An alternative to these is to use the StringView library (licensed as lgpl-3.0) which goal is:

  • to create a C-like interface for strings (i.e., an array of character codes — an ArrayBufferView in JavaScript) based upon the JavaScript ArrayBuffer interface
  • to create a highly extensible library that anyone can extend by adding methods to the object StringView.prototype
  • to create a collection of methods for such string-like objects (since now: stringViews) which work strictly on arrays of numbers rather than on creating new immutable JavaScript strings
  • to work with Unicode encodings other than JavaScript's default UTF-16 DOMStrings

giving much more flexibility. However, it would require us to link to or embed this library while TextEncoder/TextDecoder is being built-in in modern browsers.

#Support

As of July/2018:

TextEncoder (Experimental, On Standard Track)

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |    19°    |     ?     |     -     |     38

°) 18: Firefox 18 implemented an earlier and slightly different version
of the specification.

WEB WORKER SUPPORT:

Experimental, On Standard Track

 Chrome    | Edge      | Firefox   | IE        | Opera     | Safari
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     -     |     25    |     -

 Chrome/A  | Edge/mob  | Firefox/A | Opera/A   |Safari/iOS | Webview/A
 ----------|-----------|-----------|-----------|-----------|-----------
     38    |     ?     |     20    |     ?     |     -     |     38

Data from MDN - `npm i -g mdncomp` by epistemex
2 of 16
207

Although Dennis and gengkev solutions of using Blob/FileReader work, I wouldn't suggest taking that approach. It is an async approach to a simple problem, and it is much slower than a direct solution. I've made a post in html5rocks with a simpler and (much faster) solution: http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String

And the solution is:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

EDIT:

The Encoding API helps solving the string conversion problem. Check out the response from Jeff Posnik on Html5Rocks.com to the above original article.

Excerpt:

The Encoding API makes it simple to translate between raw bytes and native JavaScript strings, regardless of which of the many standard encodings you need to work with.

<pre id="results"></pre>

<script>
  if ('TextDecoder' in window) {
    // The local files to be fetched, mapped to the encoding that they're using.
    var filesToEncoding = {
      'utf8.bin': 'utf-8',
      'utf16le.bin': 'utf-16le',
      'macintosh.bin': 'macintosh'
    };

    Object.keys(filesToEncoding).forEach(function(file) {
      fetchAndDecode(file, filesToEncoding[file]);
    });
  } else {
    document.querySelector('#results').textContent = 'Your browser does not support the Encoding API.'
  }

  // Use XHR to fetch `file` and interpret its contents as being encoded with `encoding`.
  function fetchAndDecode(file, encoding) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file);
    // Using 'arraybuffer' as the responseType ensures that the raw data is returned,
    // rather than letting XMLHttpRequest decode the data first.
    xhr.responseType = 'arraybuffer';
    xhr.onload = function() {
      if (this.status == 200) {
        // The decode() method takes a DataView as a parameter, which is a wrapper on top of the ArrayBuffer.
        var dataView = new DataView(this.response);
        // The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
        var decoder = new TextDecoder(encoding);
        var decodedString = decoder.decode(dataView);
        // Add the decoded file's text to the <pre> element on the page.
        document.querySelector('#results').textContent += decodedString + '\n';
      } else {
        console.error('Error while requesting', file, this);
      }
    };
    xhr.send();
  }
</script>
🌐
DEV Community
dev.to › ollaworld › arraybuffer-in-js-56ja
ArrayBuffer in JS - DEV Community
December 8, 2024 - So, we can't manipulate ArrayBuffer directly using the memory address, and it doesn’t provide a method to manipulate data. Instead, we must use Typed Arrays or DataView to interpret and manipulate data.
🌐
Reality Ripple
udn.realityripple.com › docs › Web › JavaScript › Reference › Global_Objects › ArrayBuffer
ArrayBuffer - JavaScript - UDN Web Docs: MDN Backup
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".You cannot directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
🌐
W3Schools
w3schools.com › js › › js_arraybuffers.asp
JavaScript Array Buffer
An ArrayBuffer is fixed a block of memory, often used to store typed arrays. On top of this block, you can create different views that interpret the bits as numbers, bytes, or other data types.