How to store a byte array in Javascript
By using typed arrays, you can store arrays of these types:
Type | Value Range | Size(bytes) |
---|---|---|
Int8Array | -128 to 127 | 1 |
Uint8Array | 0 to 255 | 1 |
Uint8ClampedArray | 0 to 255 | 1 |
Int16Array | -32768 to 32767 | 2 |
Uint16Array | 0 to 65535 | 2 |
Int32Array | -2147483648 to 2147483647 | 4 |
Uint32Array | 0 to 4294967295 | 4 |
Float32Array | -3.4E38 to 3.4E38 | 4 |
Float64Array | -1.8E308 to 1.8E308 | 8 |
BigInt64Array | -2^63 to 2^63 - 1 | 8 |
BigUint64Array | 0 to 2^64 - 1 | 8 |
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 byte
s 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:
- 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). 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>
- encoding
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
Jquery Validation Using the Class Instead of the Name Value
How to Remove Youtube Branding After Embedding Video in Web Page
Store Jquery Selector in Variable
Class Methods as Event Handlers in JavaScript
Detect If User Clicks Inside a Circle
How to Retrieve If the Popstate Event Comes from Back or Forward Actions with the HTML5 Pushstate
How to Find a User's Country Using HTML5 Geolocation
Load HTML Page Dynamically into Div with Jquery
How to Make a <Div> Move Up and Down When I'm Scrolling the Page
Use a JavaScript Array to Fill Up a Drop Down Select Box
Bootstrap Modal: Is Not a Function
How to Make Recaptcha a Required Field
How to Localize a Simple HTML Website Page in My Case
How to Enable Bootstrap Tooltip on Disabled Button
How to Move All HTML Element Children to Another Parent Using JavaScript
JavaScript Getcookie Functions
JavaScript Extract Certain Properties from All Objects in Array