I am trying to write multiple files in node.js and saving their path in database. I have some strange situation with writng file-
var sessionId = req.session.Id;
var imagelength = req.files.images[0];
var lengthofarray = JSON.stringify(imagelength.length);
var arr = [];
for (var i = 0; i < lengthofarray; i++) {
var filenameas = "." + imagelength[i].filename.split('.').pop();
var newGuid = guid();
var UserFolder = "public/ImagesOfUser" + "/" + "User_" + sessionId;
var checkourstory = "public/ImagesOfUser" + "/" + "User_" + sessionId + "/" + "OurStory";
var userImages = "ImagesOfUser" + "/" + "User_" + sessionId + "/" + "OurStory" + "/" + newGuid + filenameas;
if (!fs.existsSync(UserFolder)) {
fs.mkdir(UserFolder);
}
if (!fs.existsSync(checkourstory)) {
fs.mkdir(checkourstory);
}
fs.readFile(imagelength[i].path, function (err, data) {
fs.writeFile(checkourstory + "/" + newGuid + filenameas, data, function (err) {
});
});
connection.init();
connection.query('insert into usergallary (UserId,Image_Path,SectionName) values(?,?,?)', [sessionId, userImages, "OurStory"], function (reqest, reslt) {
});
}
Note I am saving file's path in database that is coming through loop and it saves multiple entries for files. But when I try to write files in loop within same loop where database is being executed as it is here above then it doesn't write multiple times.
It only writes one file from loop. How do I write multiple files coming in array?