Following the standard example from the NodeJS 'ws' package: https://www.npmjs.com/package/ws
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});
I am wondering how to do anything with the data that I receive on the on.('message')
method. The returned data looks like it is somehow encoded (Arraybuffered?):
console.log(data)
produces: <Buffer 7b 22 6b 65 65 70 41 6c 69 76 65 22 3a 22 31 22 7d>
console.log(data.toString())
produces: {"keepAlive":"1"}
. How do I go about converting this data into an object, where the keys would be accessible? e.g.:
ws.on('message', function message(data) {
//Some conversion needs to happen here
if(data.thatKey){
doThis();
}
});
.toString()
seems to correctly convert the data into a readable string, but this string can't be parsed back into an object. I have also tried JSON.stringify()
and then JSON.parse()
but this also produces a string that cannot be converted into an object.
I have also tried something like this:
function ab2str(buf) {
return decoder.decode(new Uint8Array(buf));
}
Which also returns a string that cannot be converted into an object (it seems).
CodePudding user response:
You are getting a string of text (in this case json) and you should var obj = JSON.parse(data)
which in case of your data would look like:
// console.log(data.toString()) produces: {"keepAlive":"1"}
var data = `{"keepAlive":"1"}`;
var obj = JSON.parse(data);
console.log(obj)
CodePudding user response:
For some reason, the data I get from the socket is a UInt8Array. This worked for me:
ws.on('message', function message(data) {
const newdata = JSON.parse(JSON.stringify(data));
const enc = new TextDecoder("utf-8");
const arr = new Uint8Array(newdata.data);
const decoded = enc.decode(arr);
const object = JSON.parse(decoded);
if(object.keepAlive === '1'){
console.log('success');
}
});