1

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.

Vo Thanh Thang
  • 330
  • 1
  • 5
  • 16
  • You're wrong when you say you did not declare `done` anywhere. You declared it with `done = true`. In javascript, `done = true` **declares a global variable `done`** while `var done = true` *declares a **local** variable `done`* – slebetman Jun 16 '15 at 01:51
  • While you didn't properly declare `done`, you assigned a value to it anyway. As a default behavior, if a variable by the name being assigned isn't found, it is established as a global. [What is the function of the var keyword and when to use it (or omit it)?](http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it) – Jonathan Lonowski Jun 16 '15 at 01:56
  • @VoThanhThang: That is an interesting question. Are you sure that's what's happening. From what I can tell. It doesn't have any effect on the code. – slebetman Jun 16 '15 at 02:06
  • @slebetman, sorry, my mistake, I have deleted my comment. Thanks you so much for your explain. – Vo Thanh Thang Jun 16 '15 at 02:08

1 Answers1

1

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.

Yuri Zarubin
  • 11,439
  • 4
  • 30
  • 33