OutputFileOptimiser.coffee 1002 B

123456789101112131415161718192021222324252627282930313233
  1. fs = require "fs"
  2. Path = require "path"
  3. spawn = require("child_process").spawn
  4. logger = require "logger-sharelatex"
  5. module.exports = OutputFileOptimiser =
  6. optimiseFile: (src, dst, callback = (error) ->) ->
  7. # check output file (src) and see if we can optimise it, storing
  8. # the result in the build directory (dst)
  9. if src.match(/\.pdf$/)
  10. OutputFileOptimiser.optimisePDF src, dst, callback
  11. else
  12. callback (null)
  13. optimisePDF: (src, dst, callback = (error) ->) ->
  14. tmpOutput = dst + '.opt'
  15. args = ["--linearize", src, tmpOutput]
  16. logger.log args: args, "running qpdf command"
  17. proc = spawn("qpdf", args)
  18. stdout = ""
  19. proc.stdout.on "data", (chunk) ->
  20. stdout += chunk.toString()
  21. proc.on "error", callback
  22. proc.on "close", (code) ->
  23. if code != 0
  24. logger.warn {directory, code}, "qpdf returned error"
  25. return callback null
  26. fs.rename tmpOutput, dst, (err) ->
  27. if err?
  28. logger.warn {tmpOutput, dst}, "failed to rename output of qpdf command"
  29. callback err