I am trying to make a file upload using Node.js and the Formidable module.
npm install formidable
And then I made this, please read the notes - where I can explain what each function does and describes the algorithm:
// get access to the files that were sent;
// at this time I don't want the files to be uploaded yet;
// in the next function I will validate those files.
function form_parse() {
form.parse(req, (err, fields, files) => {
if (err) return req.Cast.error(err);
if (Object.keys(files).length==0) return req.Cast.badRequest();
req.files = files;
return validate_files();
});
}
// I made an object with options to validate against the
// files. it works and continues to the process_files()
// function only whether files are verified.
function validate_files() {
let limitations = require('../uploads-limitations');
try {
limitation = limitations[req.params.resource];
} catch(err) {
return req.Cast.error(err);
}
let validateFiles = require('../services/validate-files');
validateFiles(req, limitation, err => {
if (err) return req.Cast.badRequest(err);
return process_files();
});
}
// here is the problem - form.on doesn't get fired.
// This is the time I want to save those files - after
// fully verified
function process_files() {
form.on('file', function(name, file) {
console.log(`file name: ${file.name}`);
file.path = path.join(__dirname, '../tmp_uploads/' + file.name);
});
form.on('error', err => {
return req.Cast.error(err);
});
form.on('end', () => {
console.log(`successfully saved`);
return req.Cast.ok();
});
}
form_parse();
As you can see and as I have described - the validation works but when I want to actually save those files the form.on (events) are not getting fired.