aboutsummaryrefslogtreecommitdiff
path: root/controllers/uploadController.js
diff options
context:
space:
mode:
authorBobby Wibowo <[email protected]>2018-03-18 23:32:59 +0700
committerBobby Wibowo <[email protected]>2018-03-18 23:32:59 +0700
commit5be27c129d66ac9f872f11031e9887502559ed4e (patch)
treeb12b2a86977be28eb3352356fbf2be8476075f22 /controllers/uploadController.js
parentPatch to allow "retries" when generating random name (diff)
downloadhost.fuwn.me-5be27c129d66ac9f872f11031e9887502559ed4e.tar.xz
host.fuwn.me-5be27c129d66ac9f872f11031e9887502559ed4e.zip
Uses async
Diffstat (limited to 'controllers/uploadController.js')
-rw-r--r--controllers/uploadController.js21
1 files changed, 10 insertions, 11 deletions
diff --git a/controllers/uploadController.js b/controllers/uploadController.js
index ec9e066..51c0cf4 100644
--- a/controllers/uploadController.js
+++ b/controllers/uploadController.js
@@ -17,18 +17,17 @@ const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, uploadDir);
},
- filename: function(req, file, cb) {
- for (let i = 0; i < maxTries; i++) {
+ filename: function(req, file, cb) {
+ const access = i => {
const name = randomstring.generate(config.uploads.fileLength) + path.extname(file.originalname);
- try {
- fs.accessSync(path.join(uploadDir, name));
- console.log(`A file named "${name}" already exists (${i + 1}/${maxTries}).`);
- } catch (err) {
- // Note: fs.accessSync() will throw an Error if a file with the same name does not exist
- return cb(null, name);
- }
- }
- return cb('Could not allocate a unique file name. Try again?');
+ fs.access(path.join(uploadDir, name), err => {
+ if (err) return cb(null, name);
+ console.log(`A file named "${name}" already exists (${++i}/${maxTries}).`);
+ if (i < maxTries) return access(i);
+ return cb('Could not allocate a unique file name. Try again?');
+ });
+ };
+ access(0);
}
});