What is wrong with Nodejs?

161 views Asked by At

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.

1

There are 1 answers

0
Yuri Zarubin On BEST ANSWER

What done=true is doing, is declaring a global variable called done. In order for it to not be a global variable, use the var key word e.g. var done = true. It is generally regarded as a bad idea to declare global variables. JavaScript has an optional mode called strict mode, that prevents you from accidentally declaring global variables https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode

It is standard practice to use strict mode everywhere, and is generally declared at the top of a .js file.