title: How exactly does a callback function work in nodejs?
body: <p>I went through many examples of nodejs with callbacks, but didn't understand how exactly they work. I know that they're executed after the function, of which they're a part of is done, but I didn't understand callbacks as a function. Let me give an example:</p>
  
  <pre><code>function processData (callback) {
    fetchData(function (err, data) {
      if (err) {
        console.log("An error has occured. Abort everything!");
        callback(err);
      }
      data += 1;
      callback(data);
    });
  }
  </code></pre>
  
  <p>Here, what how do <strong>callback(err)</strong> and <strong>callback(data)</strong> execute, as in, is it an alias for some other function to which we're passing the parameters - err/ data? If so, which function does it call when we write callback(parameter)?</p>
  
  <p>Here's another example :</p>
  
  <pre><code>var express =   require("express");
  var bodyParser =    require("body-parser");
  var multer  =   require('multer');
  var app =   express();
  app.use(bodyParser.json());
  var storage =   multer.diskStorage({
    destination: function (req, file, callback) {
      callback(null, './uploads');
    },
    filename: function (req, file, callback) {
      callback(null, file.fieldname + '-' + Date.now());
    }
  });
  var upload = multer({ storage : storage }).array('userPhoto',2);
  
  app.get('/',function(req,res){
        res.sendFile(__dirname + "/index.html");
  });
  
  app.post('/api/photo',function(req,res){
      upload(req,res,function(err) {
          //console.log(req.body);
          //console.log(req.files);
          if(err) {
              return res.end("Error uploading file.");
          }
          res.end("File is uploaded");
      });
  });
  
  app.listen(3000,function(){
      console.log("Working on port 3000");
  });
  </code></pre>
  
  <p>Again I sort of understood the other type of callback - suppose, here fs.readdir</p>
  
  <pre><code>fs.readdir(path, function (err, files) {
      if (err)  console.error(err);
      for (var i = 0; i&lt;files.length; i++)  console.log(files[i];
  }
  console.log("done");
  </code></pre>
  
  <p>I know how this executes, most probably it'll print <strong>done</strong> first, and then prints the list of files, as soon as readdir is executed with files having the list of files. </p>
  
  <p>But I didn't exactly understand the first and second code snippet. Can someone please explain that in simple terms, specific to the multer code snippet?</p>