download-images.js 1.3 KB

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