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