Good evening.

I use to get data (pictures) busboy.

I get the data like this:

var buffer = Buffer.allocUnsafe(filesize); req.recvSize = 0; file.on('data', function (data) { buffer.write(data,req.recvSize,data.length); req.recvSize += data.length; }); 

The output is such an error:

 buffer.js:761 return this.utf8Write(string, offset, length); ^ TypeError: Argument must be a string at TypeError (native) at Buffer.write (buffer.js:761:21) 

The variant with concat does not suit me, since I initially know the file size and then I do not need unnecessary actions (because of this, I decided to immediately write to the buffer).

copy also doesn’t really want to be used, as yet write writes data directly, without unnecessary copying (if you are ready to challenge this, I will be glad to read your opinion in the comments)

How can you solve such an error or how will it be more correct to accept data?

  • I'm not very familiar with busboy , but judging by the error, you have a data argument not of type string , in the event handler for the file.on event. A must be of type string . - Stepan Kasyanenko
  • one
    you need to look at what data is and where it comes from, if there is exactly a valid string, then you can write like this: buffer.write (data.toString (), req.recvSize, data.length); - pnp2000

1 answer 1

Not very clear on a piece of code that is file . Most likely this is your request to the server. Check if you have specified the encoding somewhere. Something of type res.setEncoding('utf8') In this case, just at the data event you will receive a string object, not a Buffer.

But in general, you don’t win too much, regarding the concat of the buffer array Buffer.concat(buffers) . Because in the data event, you already receive a ready selected Buffer object, and there is not much difference when copying it initially, or at the very end. In addition, despite the stated length of the file, you actually may not have come so much data (the connection is broken, the server changes its mind), and you have already allocated memory for all this.

By the way, inside Buffer.concat uses copy , to copy data, not write