download-images.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env node
  2. 'use strict'
  3. const fs = require('node:fs')
  4. const path = require('node:path')
  5. const request = require('request')
  6. const filePath = path.join(__dirname, '../src/pages/_data/photos.json')
  7. const photos = JSON.parse(fs.readFileSync(filePath, 'utf8'))
  8. const urlTitle = (str) => {
  9. str = str
  10. .toLowerCase()
  11. .replaceAll('&', 'and')
  12. .replace(/[^[a-z0-9-]/g, '-')
  13. .replace(/-+/g, '-')
  14. return str
  15. }
  16. const download = function (uri, filename, callback, error) {
  17. request.head(uri, function (err, res, body) {
  18. request(uri).pipe(fs.createWriteStream(filename))
  19. .on('close', callback)
  20. .on('error', error)
  21. })
  22. }
  23. async function downloadPhotos() {
  24. for (const key in photos) {
  25. const photo = photos[key]
  26. let filename, i = 1;
  27. do {
  28. filename = `${urlTitle(photo['title'])}${i > 1 ? `-${i}` : ''}.jpg`
  29. i++
  30. } while (fs.existsSync(path.join(__dirname, `../src/static/photos/${filename}`)))
  31. await new Promise((resolve, reject) => {
  32. download(photo['path'], path.join(__dirname, `../src/static/photos/${filename}`), function () {
  33. resolve()
  34. }, function () {
  35. reject()
  36. });
  37. })
  38. photos[key]['file'] = filename
  39. photos[key]['horizontal'] = photo['width'] > photo['height']
  40. }
  41. fs.writeFileSync(filePath, JSON.stringify(photos))
  42. }
  43. downloadPhotos();