download-images.mjs 1.4 KB

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