disk.js 1.6 KB

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