OutputFileOptimiser.coffee 1.3 KB

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