2017-02-10 47 views
0

为什么下载的图像格式不正确?为什么下载的图像格式不正确?

import * as fs from 'fs'; 
import * as request from 'request-promise-native'; 

const download = async (url) => { 
    console.log(`Downloading ${url}`); 
    const options = { 
    url, 
    resolveWithFullResponse: true, 
    }; 
    const response = await request.get(options); 
    console.dir(response.headers); 
    return fs.writeFileSync('image.jpg', response.body); 
}; 


const main = async() => { 
    try { 
    await download('https://dz2cdn1.dzone.com/storage/rc-covers/3339976-refcard-cover141.png'); 
    } catch (e) { 
    console.error(e); 
    } 
}; 

main().then(() => console.log('success')).catch((e) => console.log(e)); 

生成的图像格式不正确,无法打开。任何想法是什么导致这个问题,以及如何解决它?

+0

[使用请求获取Node.js中的二进制内容]可能重复(http://stackoverflow.com/questions/14855015/getting-binary-content-in-node-js-using-request) – GilZ

回答

1

默认情况下,request将响应视为utf-8文本。如果您想以二进制形式保存响应(具体为单个Buffer),则需要在request()选项中明确设置encoding: null

+0

谢谢!这解决了它! – Kiril

相关问题