I am trying to upload a file/store using node and saving the file in Gird FS. Below is the code sample. The upload functionality works perfectly. Due to node's async nature, response is immediately sent back to the browser. I want to hold the response until the callback function gets executed. Note : i also tried to send final response inside call back function but still it did not work.
Please shed some ideas.
const multer = require("multer");
const GridFsStorage = require("multer-gridfs-storage");
const mongoose = require("mongoose");
mongoose.connect(CONFIG.dbConfig, {useNewUrlParser: true, useUnifiedTopology: true} );
var storage = new GridFsStorage({
url: CONFIG.dbConfig,
options: { useNewUrlParser: true, useUnifiedTopology: true },
file: (req, file) => {
return {
bucketName: "xyz",
filename: `${file.originalname}`
};
}
});
const viewPage = (req, res) => {
try {
var uploadFile = multer({ storage: storage }).single("file");
uploadFile(req, res, function(err) {
if (req.file == undefined) {
return res.send(`You must select a file.`);
}
/* code to save anthother Schema */
fileDetails.save(function(err) {
if (err) throw err;
});
});
return res.send(`File has been uploaded.`);
} catch (error) {
console.log(error);
return res.send(`Error when trying upload image: ${error}`);
}
};
module.exports = {
getPage: viewPage
};