0

I have code like this

var reader = new FileReader();
reader.onload = function(){
    socket.emit('test', reader.result);
};
reader.readAsArrayBuffer(uploadHandler.files[0]);

it gets file from

<input type="file" />

and "converts" it to ArrayBuffer, then sends trough WebSockets (Socket.io used) to Node.js server, where i am trying to save it like this

socket.on('test', function(request) {
    require('fs').writeFileSync('../files/test.png', Buffer.from(request));
});

But i get TypeError: this is not a typed array.

server > 04-29 12:21:22: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52   │
00 00 01 1e 00 00 00 66 08 06 00 00 00 1d cf fe ce 00 00 0c 13 69 43 43 50 49 43   │
43 20 50 72 6f 66 69 ... >                                                         │
server > TypeError: this is not a typed array.                                     │
server >     at Function.from (native)                                             │
server >     at Socket.<anonymous> (/home/htdocs/socket/server/server.js:201:65)   │
server >     at emitOne (events.js:77:13)                                          │
server >     at Socket.emit (events.js:169:7)                                      │
server >     at /home/htdocs/socket/server/node_modules/socket.io/lib/socket.js:5  │
03:12                                                                              │
server >     at nextTickCallbackWith0Args (node.js:419:9)                          │
server >     at process._tickDomainCallback (node.js:389:13)

Node.js version is LTS 6.10.2, so as far as i understood i don't need to make Uint8Array from ArrayBuffer, and just can use Buffer.from method, but error still here.

1 Answer 1

2

Found out, regardless how you send your file to Socket.io, as ArrayBuffer or File on server side it comes as a Buffer already, so there is no need to call Buffer.from and you can just write

socket.on('test', function(buffer) {
    require('fs').writeFileSync('../files/test.png', buffer);
});

And it works :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.