Convert string to buffer Node

node.js

node.js Problem Overview


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

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

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

Solution 3 - node.js

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

Solution 4 - node.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAniketView Question on Stackoverflow
Solution 1 - node.jsJohn ZwinckView Answer on Stackoverflow
Solution 2 - node.jsEmdadul SawonView Answer on Stackoverflow
Solution 3 - node.jsmidoView Answer on Stackoverflow
Solution 4 - node.jsKrishan Kumar MouryaView Answer on Stackoverflow