Search code examples
javascriptnode.jsexpressnodemon

Express route functions not hoisted


Could someone please explain to me why my Express routes are not hoisted? I'm constantly seeing the following error thrown:

throw new TypeError('Router.use() requires middleware functions');

The following file does not produce the error:

var express        = require('express'),
    router         = express.Router()

var loadWidget = function (req, res, next) {

    req.widget = { text: 'Widget' };

    return next();
};

var sendWidget = function (req, res, next) {

    return res.status(200).send(req.widget);
};

router.use(loadWidget);

router.get('/', sendWidget);

module.exports = router;

However, changing the order of the methods, as in the file below, does throw the error:

var express        = require('express'),
    router         = express.Router()

router.use(loadWidget);

router.get('/', sendWidget);

var loadWidget = function (req, res, next) {

    req.widget = { text: 'Widget' };

    return next();
};

var sendWidget = function (req, res, next) {

    return res.status(200).send(req.widget);
};

module.exports = router;

I would like to have my file with the operations at the head of the file (use, get, post, etc.) with the actual bodies of the functions below.

On a side note, the error is thrown when I first invoke the app. Sending rs with nodemon does not throw the error:

Causes error:

NODE_APP='app01' nodemon ./server/server

No error:

rs

Solution

  • Function declarations are hoisted in javascript but function expressions are not. Function expression is:

    var fn = function() {};
    

    And function declration:

    function fn() {};