Null when parsing Uint8Array in Typescript

104 Views Asked by At

I have the following object that I get as response when calling aws Lambda client from nodeJS.

{
'$metadata': {
    httpStatusCode: 200,
    requestId: '1245',
    extendedRequestId: undefined,
    cfId: undefined,
    attempts: 1,
    totalRetryDelay: 0
  },
  ExecutedVersion: '$LATEST',
  Payload: Uint8Array(4) [ 110, 119, 106, 108 ],
  StatusCode: 200
}

Below is the piece of code I have to read the payload array.

const res = await myclient.send(command);
const error = res.FunctionError;
console.log("res", res);
if (error) {
   throw new Error(`Error invoking lambda:${error}`);
}
if (!res.Payload) {
   throw new Error('Payload is empty');
}
const resultString = JSON.parse(new TextDecoder('utf-8').decode(res.Payload));
console.log("resultString", resultString);

However when the code runs, I get resultString null. What am I doing wrong here? How can I correctly read the payload array? Appreciate any advice.

1

There are 1 best solutions below

0
On

Not sure what is going on. I tried a simple example to see what was going on.

const array = new Uint8Array(4);
array[0] = 110;
array[1] = 119;
array[2] = 106;
array[3] = 108;

const res = new TextDecoder('utf-8').decode(array);

console.log(res); // nwjl

So if the data you are getting is correct, omitting the JSON.parse gives me a string at least. But including it throws an error.