ImageOptimiser.coffee 1.1 KB

1234567891011121314151617181920212223242526272829
  1. PngCrush = require('pngcrush')
  2. fs = require("fs")
  3. logger = require("logger-sharelatex")
  4. module.exports =
  5. compressPng: (localPath, callback)->
  6. optimisedPath = "#{localPath}-optimised"
  7. startTime = new Date()
  8. logger.log localPath:localPath, optimisedPath:optimisedPath, "optimising png path"
  9. readStream = fs.createReadStream(localPath)
  10. writeStream = fs.createWriteStream(optimisedPath)
  11. readStream.on "error", (err)->
  12. logger.err err:err, localPath:localPath, "something went wrong getting read stream for compressPng"
  13. callback(err)
  14. writeStream.on "error", (err)->
  15. logger.err err:err, localPath:localPath, "something went wrong getting write stream for compressPng"
  16. callback(err)
  17. myCrusher = new PngCrush()
  18. myCrusher.on "error", (err)->
  19. logger.err err:err, localPath:localPath, "error compressing file"
  20. callback err
  21. readStream.pipe(myCrusher).pipe(writeStream)
  22. writeStream.on "finish", ->
  23. timeTaken = new Date() - startTime
  24. logger.log localPath:localPath, timeTaken:timeTaken, "finished converting file"
  25. fs.rename optimisedPath, localPath, callback