2
votes

Using electron I am trying to write out some bytes on a TCP socket. I am using Buffer.from to convert to buffer before calling write, but am still getting the above error. I have simplified it down to just creating an empty ArrayBuffer and calling Buffer.from

var abuff = new ArrayBuffer(8 + encodedBuffer.length);
console.log(Buffer.from(abuff));
socket.write(Buffer.from(abuff));

TypeError: Invalid data, chunk must be a string or buffer, not object The console.log shows the following:

Uint8Array(51) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

and not Buffer?

Versions in electron: ares:"1.10.1-DEV" atom-shell:"1.7.9" chrome:"58.0.3029.110" electron:"1.7.9" http_parser:"2.7.0" modules:"54" node:"7.9.0" openssl:"1.0.2k" uv:"1.11.0" v8:"5.8.283.38" zlib:"1.2.11"

For anyone seeing this type of problem - This code was in the "renderer" process of Electron, the problem was the Buffer object in the "renderer" did not create a Buffer object from Buffer.from.

To solve I used IPC to send request from the renderer to the main process and let the main process manage the socket communication.

3

3 Answers

1
votes

As is said in error, chunk can be only type string or buffer.
So we have few solutions for your problem.
First one, just convert your object to string with JSON.stringify(<your data to send>), and than you can decode it on the other side.
Or you can use object mode, more here.

I've tried to test your code and it works.

var net = require('net');
var encodedBuffer = 9;
var abuff = new ArrayBuffer(8 + encodedBuffer.length);

var server = net.createServer(function(socket) {
  socket.write('Echo server\r\n');
  console.log(Buffer.from(abuff));
  socket.write(Buffer.from(abuff));
  socket.pipe(socket);
});

server.listen(1337, '127.0.0.1');

And when I start app and make request to server from another command line session nc 127.0.0.1 1337, I see output in server window.

1
votes

The issue was that I was trying to use the socket code in the renderer process of the electron app and the buffer implementation there is different than for the main process. When I moved the socket send to the main process it worked just as expected.

0
votes

I had same problem in node version 8.9.4, I changed node version to 11.11.0. and the problem is disappeared.