node.js 将字符串转换为缓冲区节点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37436824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:15:36  来源:igfitidea点击:

Convert string to buffer Node

node.js

提问by Aniket

I am using a library which on call of a function returns the toString of a buffer.

我正在使用一个库,它在调用函数时返回缓冲区的 toString。

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

但它抛出 utf-8 不是一个函数。当我做

var buf = Buffer.from(bufStr);

It throws TypeError : this is not a typed array.

它抛出 TypeError :这不是类型化数组。

Thanks

谢谢

回答by John Zwinck

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.

但这有点傻,所以另一个建议是从被调用函数中复制最少量的代码,以允许您访问原始缓冲区。这可能很容易或相当困难,具体取决于该库的详细信息。

回答by mido

Note:Just reposting John Zwinck's comment as answer.

注意:只需重新发布 John Zwinck 的评论作为答案。

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:

一个问题可能是您使用的是旧版本的 Node(目前,我无法升级,代码库被v4.3.1)。这里的简单解决方案是,使用已弃用的方式:

new Buffer(bufferStr)

回答by Emdadul Sawon

You can use Buffer.from()to convert a string to buffer. More information on this can be found here

您可以使用Buffer.from()将字符串转换为缓冲区。可以在此处找到有关此的更多信息

var buf = Buffer.from('some string', 'encoding');

for example

例如

var buf = Buffer.from(bStr, 'utf-8');

回答by Krishan Kumar Mourya

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