-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (54 loc) · 1.56 KB
/
index.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const pexels = require('pexels')
const download = require('image-downloader');
const path = require('path')
const csv = require('csv-parser')
const fs = require('fs')
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.Console({
format: winston.format.simple(),
})
],
});
function delay(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
const pexelsClient = pexels.createClient(process.env.API_KEY)
async function downloadPhoto(animal) {
const photoName = animal.English
const photoFileName = path.join(__dirname, 'images', `${photoName}-${animal.Mandarin}.jpg`)
// Check if the file exists
if (fs.existsSync(photoFileName)) {
// logger.info(`File exists at: ${photoFileName}`)
return
}
const photoSearch = await pexelsClient.photos.search({
query: photoName,
orientation: 'landscape',
size: 'medium'
})
if (photoSearch.photos.length < 1) {
logger.error(`Cannot find image for ${photoName}`)
await delay(2000)
return;
}
const photoSrc = photoSearch.photos[0].src.large;
await download.image({
url: photoSrc,
dest: photoFileName,
extractFilename: false
})
}
const animals = [];
fs.createReadStream(path.join(__dirname, 'data', 'mandarin-animal-names.csv'))
.pipe(csv())
.on('data', (data) => animals.push(data))
.on('end', async () => {
for (const animal of animals) {
await downloadPhoto(animal)
}
});