[node.js] 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

This question is related to node.js

The answer is


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


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');

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"));