I have a third party api which returns binary data set which is converted using BigEndian(confirmed). Dataset consist of set of students with their name and Id.
I am trying to read the content and update the local storage at the moment and I wrote a javascript file to read the data and display in a console like below.
var pointer = 0;
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.test.com/students", true);
xhr.onload = function () {
var data = xhr.response;
pointer++;
// Read students
var classesCount = data.readUInt32BE(pointer);
pointer+=4;
console.log('classesCount:' + classesCount);
for (let classId = 0; classId < classesCount; classId++) {
var classNameLength = data.readUInt8(pointer);
pointer++;
var classNameUTF8 = data.slice(pointer, pointer + classNameLength);
pointer += classNameLength;
var className = new TextDecoder().decode(classNameUTF8);
console.log(className);
// display students per class
var classStudentCount = data.readUInt32BE(pointer);
pointer += 4;
//console.log('Class Students: ' + classStudentCount);
for (let classStudentId = 0; classStudentId < classStudentCount; classStudentId++) {
var studentIdLength = data.readUInt8(pointer);
pointer++;
var studentIdUTF8 = data.slice(pointer, pointer + studentIdLength);
pointer += studentIdLength;
var studentId = new TextDecoder().decode(studentIdUTF8);
var studentNameLength = data.readUInt8(pointer);
pointer++;
var studentNameUtf8 = data.slice(pointer, pointer + studentNameLength);
pointer += studentNameLength;
var studentName = new TextDecoder().decode(studentNameUtf8);
pointer += 4;
console.log(studentId + ' - ' + studentName);
}
}
};
xhr.setRequestHeader(
"Authorization",
"Bearer {token}"
);
xhr.send();
In order to apply this on angular, I tried with DataView, which supports BigEndian, but I was not able to read the content, which I did using above code.
var res = req.response;
var buffer = new ArrayBuffer(res.length);
var view = new DataView(buffer);
console.log('Version: ' + view.getUint8(offset));
offset++;
var classCount = view.getUint32(offset);
offset += 4;
console.log(classCount);
Apart from that, I tried Smart Buffer, but when trying to slice the data, slice function does not support on Smart Buffer.
What am I doing wrong here? Can anyone point the error?.
Thanks in advance.