Javascript 使用请求在 Node.js 中获取二进制内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14855015/
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
Getting binary content in Node.js using request
提问by GilZ
I was trying to GETa binary data using request, and had something like:
我试图GET使用二进制数据request,并且有类似的东西:
var requestSettings = {
method: 'GET',
url: url,
};
request(requestSettings, function(error, response, body) {
// Use body as a binary Buffer
}
But bodywas always a few bytes different from expected. After further investigation I found out that requestassumed bodyis string and replaced all non-unicode bytes.
但body总是与预期的几个字节不同。经过进一步调查,我发现request假定body是字符串并替换了所有非 unicode 字节。
I tried to add
我试着添加
encoding: 'binary'
to requestSettingsbut it didn't help.
到requestSettings,但它并没有帮助。
How can I get the binary data?
我怎样才能得到二进制数据?
回答by GilZ
OK, after a lot of digging, I found out that requestSettingsshould have:
好吧,经过大量挖掘,我发现requestSettings应该有:
encoding: null
And then bodywill be of type Buffer, instead of the default, which is string.
然后body将是 type Buffer,而不是默认值,即字符串。
回答by gismatthew
The accepted answer didn't solve my problem. I somehow figured that gzip: trueworked.
接受的答案并没有解决我的问题。我以某种方式认为这gzip: true有效。

