Hey Guys an express app which gets a file via Post and should than save it, send it to another server and delete it afterwards. This whole process works but if i log the steps the programm produces i'm confused because i get a outprint for delete even before the file is saved. So for now i want to know if there is the possibility to really call the 3 functions step by step. Because deleting a file before it is saved isnt right. so here is my code and i hope you can help me.
server.post("/upload", function (req, res) {
if (!req.files) {
res.send("No file uploaded");
} else {
//the Filepointer points to the whole File object which can contain multiple files
var filePointer = req.files;
console.log(filePointer);
res.send("Files uploaded");
let key;
for (key of Object.keys(filePointer)) {
//single file uploaded so no json Object else get number of elements in the Array and loop over them
if ((typeof filePointer[key][0]) === 'undefined') {
//if theres only one File in the Object you can directly access the keys
var file = filePointer[key];
//console.log("var is undefined");
console.log(file["name"]);
var uploadPath = __dirname + "/uploads/" + file["name"];
console.log(uploadPath);
saveFile(uploadPath, file);
sendToTika();
deleteFile(uploadPath);
} else {
let index;
for (index of Object.keys(filePointer[key])) {
//with multiple files you need to access the keys with an indey i
var file = filePointer[key][index];
console.log(file["name"]);
var uploadPath = __dirname + "/uploads/" + file["name"];
console.log(uploadPath);
saveFile(uploadPath, file);
sendToTika();
deleteFile(uploadPath);
}
}
}
}
});
server.listen(3000, function () {
console.log("server is listening on port 3000");
})
function saveFile(UploadPath, file) {
file.mv(UploadPath, function (err) {
if (err) {
console.log(err);
} else {
console.log("file uploaded and saved" + UploadPath);
}
})
}
function sendToTika() {
console.log("tika Function");
}
//TODO: check if sync or async is better for this task
function deleteFile(deletePath) {
fs.unlink(deletePath, function (error) {
if (error) {
console.log(error);
}
console.log("deleted" + deletePath);
})
}
the console log is:
tika Function
deleted
file uploaded and saved
EDIT: Hey Guys first of all thank you all for your answers i will take a look at promises!