Syntax of app.use(express.static('public'))


The code app.use(express.static('public')) is used in express apps to set a folder for static files access. I don’t understand the syntax used in passing express.static('public') to app.use() function. My understanding is that when passing a function as an argument (callback) to another function, we only pass the function name. In the code app.use(express.static('public')), the function express.static() is being called inside the arguments section of app.use() function. I don’t understand the syntax used here. Is there some JavaScript syntax I am not aware of?


express.static('public') returns a middleware function when you call it.

So, this:


has the same effect as this:

const myStaticFn = express.static('public');

So, you are passing a function to app.use(). It’s just that calling express.static('public') creates a custom function that happens to know the directory it should operation on is ‘public’.

If you want to see the code for express.static(), you can see it here where you can see in the middle of the function (after some argument checking), it does this:

return function serveStatic (req, res, next) { ... }

So, that’s the function you end up passing to app.use() and you can see it has the perfect signature for a middleware function.


Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published