Skip to content Skip to sidebar Skip to footer

Nodejs: Convert String To Buffer

I'm trying to write a string to a socket (socket is called 'response'). Here is the code I have sofar (I'm trying to implement a byte caching proxy...): var http = require('http');

Solution 1:

How about this?

var responseData = Buffer.from(x, 'utf8');

from: Convert string to buffer Node

Solution 2:

Without digging very deep into your code, it seems to me that you might want to change

var responseData=x.toString();

to

var responseData=x.toString("binary");

and finally

response.write(newBuffer(toTransmit, "binary"));

Solution 3:

From the docs:

Pure Javascript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.

Raw data is stored in instances of the Buffer class. A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.

So, don't use strings for handling binary data.

Change proxy_request.write(chunk, 'binary'); to proxy_request.write(chunk);.

Omit var responseData=x.toString();, that's a bad idea.

Instead of doing substr on a string, use slice on a buffer.

Instead of doing + with strings, use the "concat" method from the buffertools.

Post a Comment for "Nodejs: Convert String To Buffer"