如何在节点中通过HTTP读取二进制文件?
我有一个Web服务器上的图像(http://example.com/img.jpg)。 我在浏览器中打开该图像并将其保存到磁盘。
如果我通过' fs
'模块( fs.readFileSync
)在节点中打开文件,我得到一个以0xff开头的缓冲区,这正是我所期望的。
我希望能够直接从HTTP请求获得相同的结果。 我正在使用“请求”模块来提出请求。
request('http://example.com/img.jpg',function(error, response, body){ //code here });
我无法弄清楚如何将响应或正文转换为与FileSystem相同的Buffer。 我错过了什么?
您可以通过将encoding
设置为null
来获得Buffer
:
request('http://example.com/img.jpg', { encoding: null }, function(error, response, body){ console.log(Buffer.isBuffer(body)); // true });
request
将任何其他值作为 buffer.toString()
的参数处理,默认值undefined
为"utf8"
。