下载没有文件结尾 nodejs 的文件

问题描述

例如:https://preview.redd.it/04o5k2n06zd71.jpg?width=960&crop=smart&auto=webp&s=7baa25e7e1bde3436cb2a265e2fc8c6cb9a758ee

如何将该图像下载/加载到缓冲区

注意: 结局总是不同的。

解决方法

以下是使用 got() 库的 nodejs 实现:

const got = require('got');

const url =
    'https://preview.redd.it/04o5k2n06zd71.jpg?width=960&crop=smart&auto=webp&s=7baa25e7e1bde3436cb2a265e2fc8c6cb9a758ee';

got(url,{ responseType: 'buffer' }).then(result => {
    // result.body contains a Buffer object with the image in it
    console.log(`content-type: ${result.headers['content-type']}`);
    console.log(`isBuffer: ${Buffer.isBuffer(result.body)}`);
    console.log(result.body);
}).catch(err => {
    console.log(err);
});

您可以直接使用 nodejs 运行此代码(安装 got() 库后)。当我运行它时,它会生成以下输出:

content-type: image/jpeg
isBuffer: true
<Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e2 02 1c 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 02 0c 6c 63 6d 73 02 10 00 00 ... 89335 more bytes>