Convert string to buffer Node
I am using a library which on call of a function returns the toString of a buffer.
The exact code is
return Buffer.concat(stdOut).toString('utf-8');
But I don't want string version of it.
I just want the buffer
So how to convert string back to buffer.
Something like if
var bufStr = Buffer.concat(stdOut).toString('utf-8');
//convert bufStr back to only Buffer.concat(stdOut).
How to do this?
I tried doing
var buf = Buffer.from(bufStr, 'utf-8');
But it throws utf-8 is not a function. When I do
var buf = Buffer.from(bufStr);
It throws TypeError : this is not a typed array.
Thanks
You can do:
var buf = Buffer.from(bufStr, 'utf8');
But this is a bit silly, so another suggestion would be to copy the minimal amount of code out of the called function to allow yourself access to the original buffer. This might be quite easy or fairly difficult depending on the details of that library.
You can use Buffer.from()
to convert a string to buffer. More information on this can be found here
var buf = Buffer.from('some string', 'encoding');
for example
var buf = Buffer.from(bStr, 'utf-8');
Note: Just reposting John Zwinck's comment as answer.
One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1
). Simple solution here is, using the deprecated way:
new Buffer(bufferStr)
Note #2: This is for people struck in older version, for whom Buffer.from
does not work
This is working for me, you might change your code like this
var responseData=x.toString();
to
var responseData=x.toString("binary");
and finally
response.write(new Buffer(toTransmit, "binary"));