UNPKG

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