cleanExtracts.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict'
  2. const fs = require('fs-extra')
  3. const fsp = fs.promises
  4. const winston = require('winston')
  5. // File logger configuration
  6. const fileLogger = winston.createLogger({
  7. level: 'info',
  8. format: winston.format.json(),
  9. transports: [
  10. new winston.transports.File({ filename: 'logs/extractsRemoverService.log' }),
  11. new winston.transports.File({ filename: 'logs/extractsRemoverService.error.log', level: 'error' }),
  12. new winston.transports.Console({
  13. level: 'debug',
  14. handleExceptions: true,
  15. format: winston.format.json()
  16. })
  17. ],
  18. exitOnError: false
  19. })
  20. const { resolve: r } = require('path')
  21. const setup = async (imagesPath, shouldLog = false, logToFile = false) => {
  22. try {
  23. if (!(await fs.pathExists(imagesPath)))
  24. throw new Error(`Could not locate the image directory. Images path: ${imagesPath}`)
  25. // Get a list of all scenes
  26. const scenes = await fsp.readdir(r(imagesPath))
  27. for (const aScene of scenes) {
  28. const extractsPath = r(imagesPath, aScene, 'extracts')
  29. // Check the "extracts" dir exists
  30. if (!(await fs.pathExists(extractsPath))) {
  31. if (shouldLog) process.stdout.write(`"${aScene}/extracts" does not exist.\n`)
  32. continue
  33. }
  34. if (shouldLog) process.stdout.write(`Deleting "${aScene}/extracts"...`)
  35. await fs.remove(extractsPath)
  36. if (shouldLog) process.stdout.write(' done.\n')
  37. }
  38. if (logToFile) fileLogger.info({ log: 'The extracts remover service finished successfully.', date: new Date() })
  39. }
  40. catch (err) {
  41. if (shouldLog) console.error(err)
  42. if (logToFile) fileLogger.error({ log: { error: err.message, stack: err.stack }, date: new Date() })
  43. }
  44. }
  45. // Execute if param is set
  46. const argv = process.argv.slice(2)
  47. if (argv.includes('--execute')) {
  48. if (!process.env.IMAGES_PATH)
  49. return console.log('You must pass the "IMAGES_PATH" environment variable')
  50. setup(process.env.IMAGES_PATH, false, true)
  51. }
  52. module.exports = { setup, extractsRemoverServiceLogger: fileLogger }