Reputation: 35
i know that my following code will end up in "Upload of files was not successfull" as successAmount = successAmount+1 will not work because of async behaviour of fs.rename() ... it is clear to use promises here but i dont know how to structure the code in a better way. My aim is to send status 200, when all files are renamed. Can you help me with refactoring the code correct, i guess Promise.All() should solve it, but i dont know how ?
myMultiFileUploader: async (req, res, next) => {
console.log('Entering myMultiFileUploader');
var successAmount = 0;
for (let fileItem of req.files) {
console.log('File '+fileItem);
console.log('Filename '+fileItem.filename);
console.log('Mimetype '+fileItem.mimetype);
console.log('Orig Name '+fileItem.originalname);
//rename files
var oldName =""+process.env.FILEUPLOAD_FOLDER+""+fileItem.filename;
var newName = ""+process.env.FILEUPLOAD_FOLDER+""+fileItem.originalname;
fs.rename(oldName, newName, function (err) {
if (err) {
console.log("Could not rename uploaded file oldname "+oldName+" to newname "+newName);
}
fs.stat(newName, function (err, stats) {
if (err) {
console.log("Could not rename uploaded file");
}
else{
successAmount = successAmount+1;
}
});
});
}
if(successAmount===req.files.length-1){
return res.status(200).json({success: 'All Files have been successfully uploaded.'});
}else{
return res.status(401).json({error: 'Upload of files was not successful.'});
}
}
Upvotes: 0
Views: 1779
Reputation: 1445
I used async/await so unnecessary callbacks have been removed. If any file shows error it'll be sent to catch so no need for successAmount
count. I've attached the updated code below. Hope it helps.
const util = require('util');
const stat = util.promisify(fs.stat);
const rename = util.promisify(fs.rename);
myMultiFileUploader: async (req, res, next) => {
try {
console.log('Entering myMultiFileUploader');
await req.files.map( async (fileItem, index) => {
console.log('File '+fileItem);
console.log('Filename '+fileItem.filename);
console.log('Mimetype '+fileItem.mimetype);
console.log('Orig Name '+fileItem.originalname);
//rename files
var oldName =""+process.env.FILEUPLOAD_FOLDER+""+fileItem.filename;
var newName = ""+process.env.FILEUPLOAD_FOLDER+""+fileItem.originalname;
await rename(oldName, newName);
await stat(newName);
})
return res.json({success: 'All Files have been successfully uploaded.'});
}
catch (err) {
console.log('Error Occured : '+ err);
res.status(401).json({error: 'Upload of files was not successful.'});
}
}
Upvotes: 2