Aniket
Aniket

Reputation: 5358

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

Upvotes: 152

Views: 232451

Answers (5)

Ishan Sathe
Ishan Sathe

Reputation: 21

I think npm package must have been updated. Because the following function

let buf = Buffer.from(contractCode, 'utf-8')

seems to be working very well for me. I even cross verified by doing

console.log(String(buf))

and indeed the previous string is being returned to me

Upvotes: 0

mido
mido

Reputation: 25034

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

Upvotes: 16

Krishan Kumar Mourya
Krishan Kumar Mourya

Reputation: 2306

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

Upvotes: 4

John Zwinck
John Zwinck

Reputation: 249093

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.

Upvotes: 249

Emdadul Sawon
Emdadul Sawon

Reputation: 6077

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

Upvotes: 19

Related Questions