LocalFileWriter.coffee 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. fs = require("fs")
  2. uuid = require('node-uuid')
  3. path = require("path")
  4. _ = require("underscore")
  5. logger = require("logger-sharelatex")
  6. metrics = require("./metrics")
  7. module.exports =
  8. writeStream: (stream, key, callback)->
  9. timer = new metrics.Timer("writingFile")
  10. callback = _.once callback
  11. fsPath = @_getPath(key)
  12. logger.log fsPath:fsPath, "writing file locally"
  13. writeStream = fs.createWriteStream(fsPath)
  14. stream.pipe writeStream
  15. writeStream.on "finish", ->
  16. timer.done()
  17. logger.log fsPath:fsPath, "finished writing file locally"
  18. callback(null, fsPath)
  19. writeStream.on "error", (err)->
  20. logger.err err:err, fsPath:fsPath, "problem writing file locally, with write stream"
  21. callback err
  22. stream.on "error", (err)->
  23. logger.log err:err, fsPath:fsPath, "problem writing file locally, with read stream"
  24. callback err
  25. deleteFile: (fsPath, callback)->
  26. fs.unlink fsPath, callback
  27. _getPath : (key)->
  28. if !key?
  29. key = uuid.v1()
  30. key = key.replace(/\//g,"-")
  31. path.join(__dirname, "../../uploads/#{key}")