How to Store a Byte Array in JavaScript

How to store a byte array in Javascript

By using typed arrays, you can store arrays of these types:



































































TypeValue RangeSize(bytes)
Int8Array-128 to 1271
Uint8Array0 to 2551
Uint8ClampedArray0 to 2551
Int16Array-32768 to 327672
Uint16Array0 to 655352
Int32Array-2147483648 to 21474836474
Uint32Array0 to 42949672954
Float32Array-3.4E38 to 3.4E384
Float64Array-1.8E308 to 1.8E3088
BigInt64Array-2^63 to 2^63 - 18
BigUint64Array0 to 2^64 - 18

Java byteArray equivalent in JavaScript

If I correctly understand your question, you can use Buffer to get file contents, then read the bytes from it into your array.

Java byte type is a signed 8-bit integer, the equivalent in Node.js Buffer is buf.readInt8().

So you can read the required amount of bytes from Buffer into your array using buf.readInt8()

Or just convert it into Int8Array:

new Int8Array(new Buffer([100, 200, 255, 1, 32]));

How to declare an array of byte in Javascript

This depends on which server-side JavaScript package you use. Different packages implement different flavors of JavaScript and different versions of ECMAScript.

In NodeJS v0.6.x you have access to typed arrays. Creating one of these arrays is fairly trivial.

// creating an array of bytes, with 1024 elements
var bytes = new Uint8Array(1024);

There are other typed arrays available, handling 16 bit and 32 bit integers.

// creating an array of 16 bit integers, with 128 elements
var array_16bit = new Uint16Array(128);

// creating an array of 32 bit integers, with 16 elements
var array_32bit = new Uint32Array(16);

When using typed arrays, there are a few things to keep in mind. Typed arrays do not inherit the standard array prototype, and these arrays have an immutable length.

What is the best way to store a byte array in memory

It depends on how you receive the data and whether it's changed in some way:

  1. It sounds like you already have the byte array from backend. In that case I think your simple class would be the most efficient way to keep it in memory as it wouldn't consume considerable extra memory (just some few bytes for the PdfDocument object itself).
  2. You should take however into consideration whether the backend guarantees that it won't change the array later. If that's not the case, or if you want to be safe, you could create a copy with Arrays.copyOf:

    byte[] bytearray = Arrays.copyOf(bytearray, bytearray.length);

It seems like you're searching for something more fancy, but I guess your class is perfectly fine here.

Save byte array to file node JS

Use fs.writeFile to write string or byte array into a file.

  • file <String> | <Buffer> | <Integer> filename or file descriptor
  • data <String> | <Buffer> | <Uint8Array>
  • options <Object> | <String>
    • encoding <String> | <Null> default = 'utf8'
    • mode <Integer> default = 0o666
    • flag <String> default = 'w'
    • callback <Function>

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

The encoding option is ignored if data is a buffer. It defaults to 'utf8'.

const fs = require('fs');

// Uint8Array
const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data, callback);

// Buffer
fs.writeFile('message.txt', Buffer.from('Hello Node.js'), callback);

// string
fs.writeFile('message.txt', 'Hello Node.js', callback);

var callback = (err) => {
if (err) throw err;
console.log('It\'s saved!');
}

Cast int array as byte array in Javascript

You can use Int8Array, which is a typed array.

const arr = Int8Array.from([2,-76,7,2,8,69,82,88,87,2,52,50]);

Write Byte Array to a file JavaScript

Since you are requesting a binary file you need to tell XHR about that otherwise it will use the default "text" (UTF-8) encoding that will interpret pdf as text and will mess up the encoding. Just assign responseType property a value of 'blob' or the MIME type of pdf

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file

// OR xhr.responseType = 'application/pdf'; if above doesn't work

And you will access it using response property and not responseText.
So you will use arr.push(xhr.response); and it will return you a Blob.

If this doesn't work, inform me will update another solution.

Update:

var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; // tell XHR that the response will be a pdf file
xhr.onload = function() {
var blob = this.response;
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = "tst.pdf";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};

Getting byte array through input type = file

[Edit]

As noted in comments above, while still on some UA implementations, readAsBinaryString method didn't made its way to the specs and should not be used in production.
Instead, use readAsArrayBuffer and loop through it's buffer to get back the binary string :

document.querySelector('input').addEventListener('change', function() {
var reader = new FileReader(); reader.onload = function() {
var arrayBuffer = this.result, array = new Uint8Array(arrayBuffer), binaryString = String.fromCharCode.apply(null, array);
console.log(binaryString);
} reader.readAsArrayBuffer(this.files[0]);
}, false);
<input type="file" /><div id="result"></div>


Related Topics



Leave a reply



Submit