将通过 WebSockets 发送的文件作为 ArrayBuffer 保存到文件系统时出错

Error when saving file sent trough WebSockets as ArrayBuffer to file system

我有这样的代码

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

它从

获取文件
<input type="file" />

和"converts"它到ArrayBuffer,然后通过WebSockets(Socket.io使用)发送到Node.js服务器,我试图像这样保存它

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

但我得到 类型错误:这不是类型化数组。

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 版本是 LTS 6.10.2,据我所知,我不需要从 ArrayBuffer 制作 Uint8Array,只需使用 Buffer.from 方法,但错误仍然存​​在。

发现,无论你如何将文件发送到Socket.io,因为ArrayBuffer or File on server side it comes as a Buffer已经存在,所以不需要调用Buffer.from,你可以直接写

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

而且有效:)