OutputFileOptimiser.coffee 1.2 KB

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