parmentelat
parmentelat

Reputation: 117

Transferring a text file's contents over socket.io results in a ArrayBuffer object

I am a newbie with socket.io and have very little exposure to node.js as well

So I started from the simple chat app and built my way up

I can get text messages to be sent from a server to a client when the message comes from another client, like the chat demo app does

But when trying to have the server read a local file and send this contents over using io.emit, what the client side receives seems to be an instance of ArrayBuffer, which in any case confuses the JSON parser

More specifically, server side does

fs.watch('status.json', 
  function(event, filename){
    fs.readFile('status.json',
      function(err, data){
        if (err) throw err;
      io.emit("r2lab status", data);
      });
  });

and client side does

socket.on('r2lab status', function(json){
    console.log("received JSON nodes_info " + json);
    var nodes_info = JSON.parse(json);
    /* etc.. */

which at run-time triggers this in Console

received JSON nodes_info [object ArrayBuffer]
r2lab.html:1 Uncaught SyntaxError: Unexpected token o
...

As the logic works when I am getting my input by another source than a file, this all strongly suggests that the data I am getting out of readFile is not a plain string but some kind of instance that somehow makes it to the client side; like if I had opened my input file in binary or something.

Could anyone suggest a means to get JSON.parse() to be happy with this scenario ? server-side or client-side, either way would be just fine with me.

Many thanks

Upvotes: 1

Views: 1397

Answers (1)

hassansin
hassansin

Reputation: 17508

You can use Uint8Array view to access that ArrayBuffer and then convert it to string:

socket.on('r2lab status', function(data){
  var buffer = new Uint8Array(data)
  var fileString= String.fromCharCode.apply(null, buffer)
  var obj = JSON.parse(fileString)
});

Upvotes: 2

Related Questions