瀏覽代碼

Uses async

Bobby Wibowo 6 年之前
父節點
當前提交
5be27c129d
共有 1 個文件被更改,包括 10 次插入11 次删除
  1. 10 11
      controllers/uploadController.js

+ 10 - 11
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);
 	}
 });