forked from ourongxing/newsnow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfavicon.ts
48 lines (43 loc) · 1.38 KB
/
favicon.ts
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
42
43
44
45
46
47
48
import fs from "node:fs"
import { fileURLToPath } from "node:url"
import { join } from "node:path"
import { Buffer } from "node:buffer"
import { getLogos } from "favicons-scraper"
import { consola } from "consola"
import { originSources } from "../shared/sources"
const projectDir = fileURLToPath(new URL("..", import.meta.url))
const iconsDir = join(projectDir, "public", "icons")
async function downloadImage(url: string, outputPath: string, id: string) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`${id}: could not fetch ${url}, status: ${response.status}`)
}
const image = await (await fetch(url)).arrayBuffer()
fs.writeFileSync(outputPath, Buffer.from(image))
consola.success(`${id}: downloaded successfully.`)
} catch (error) {
consola.error(`${id}: error downloading the image. `, error)
}
}
async function main() {
await Promise.all(
Object.entries(originSources).map(async ([id, source]) => {
try {
const icon = join(iconsDir, `${id}.png`)
if (fs.existsSync(icon)) {
consola.info(`${id}: icon exists. skip.`)
return
}
if (!source.home) return
const res = await getLogos(source.home)
if (res.length) {
await downloadImage(res[0].src, icon, id)
}
} catch (e) {
consola.error(id, "\n", e)
}
}),
)
}
main()