/

如何在 Node 中從 URL 下載圖片

如何在 Node 中從 URL 下載圖片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os from 'os';
import fs from 'fs';
import https from 'https';

async function downloadFileFromURL(url, fileLocation) {
return await new Promise((resolve, reject) => {
https
.get(url, (response) => {
const code = response.statusCode ?? 0;

if (code >= 400) {
return reject(new Error(response.statusMessage));
}

// 處理重定向
if (code > 300 && code < 400 && !!response.headers.location) {
return await downloadFile(response.headers.location);
}

// 將文件保存到磁碟
const fileWriter = fs
.createWriteStream(fileLocation)
.on('finish', () => {
resolve({
fileLocation,
contentType: response.headers['content-type'],
});
});

response.pipe(fileWriter);
})
.on('error', (error) => {
reject(error);
});
});
}

const imageUrl = 'https://.... bla bla';
const fileLocation = os.tmpdir() + '/' + rnd(10, rnd.alphaLower);

await downloadFileFromURL(imageUrl, fileLocation);

Tags: Node, URL, 圖片下載