I am using multer to handle upload image.
app.use(multer({ dest: './public/photos',
rename: function (fieldname, filename) {
return filename+Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
//a='asass';
done=true;
}
}));
app.post('/api/photo',function(req,res){
if(done==true){ //ERROR here if I remove comment on 'a=asass' >> 'done' is not defined
console.log(req.files);
console.log(req.body);
res.end("File uploaded.");
}
});
I do NOT declare "done" variable anywhere, why this code still works?. If I remove comment on "a = asass" I get the err at above. (I do NOT declare "a" variable anywhere). I should get the error when I assign value to variables, but it does not happen.
What
done=true
is doing, is declaring a global variable calleddone
. In order for it to not be a global variable, use thevar
key word e.g.var done = true
. It is generally regarded as a bad idea to declare global variables. JavaScript has an optional mode calledstrict mode
, that prevents you from accidentally declaring global variables https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_modeIt is standard practice to use
strict mode
everywhere, and is generally declared at the top of a .js file.