disk.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var fs = require('fs')
  2. var os = require('os')
  3. var path = require('path')
  4. var crypto = require('crypto')
  5. var mkdirp = require('mkdirp')
  6. function getFilename (req, file, cb) {
  7. crypto.randomBytes(16, function (err, raw) {
  8. cb(err, err ? undefined : raw.toString('hex'))
  9. })
  10. }
  11. function getDestination (req, file, cb) {
  12. cb(null, os.tmpdir())
  13. }
  14. function DiskStorage (opts) {
  15. this.getFilename = (opts.filename || getFilename)
  16. if (typeof opts.destination === 'string') {
  17. mkdirp.sync(opts.destination)
  18. this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) }
  19. } else {
  20. this.getDestination = (opts.destination || getDestination)
  21. }
  22. }
  23. DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
  24. var that = this
  25. that.getDestination(req, file, function (err, destination) {
  26. if (err) return cb(err)
  27. that.getFilename(req, file, function (err, filename) {
  28. if (err) return cb(err)
  29. var finalPath = path.join(destination, filename)
  30. var outStream = fs.createWriteStream(finalPath)
  31. file.stream.pipe(outStream)
  32. outStream.on('error', cb)
  33. outStream.on('finish', function () {
  34. cb(null, {
  35. destination: destination,
  36. filename: filename,
  37. path: finalPath,
  38. size: outStream.bytesWritten
  39. })
  40. })
  41. })
  42. })
  43. }
  44. DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) {
  45. var path = file.path
  46. delete file.destination
  47. delete file.filename
  48. delete file.path
  49. fs.unlink(path, cb)
  50. }
  51. module.exports = function (opts) {
  52. return new DiskStorage(opts)
  53. }