var express = require('express'); var app = express(), What is express()?? is it a method or a constructor? Where does it come from

后端 未结 5 1955
南方客
南方客 2020-12-02 14:30
var express = require(\'express\'); 
var app = express();

This is how we create an express application. But what is this \'express()\'? Is it a met

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 15:31

    Ancient post. I think the original poster was confused about why the syntax to call the function exported by module express is

    var app = express() 
    

    instead of

    var app = express.express()
    

    To clarify: require() function does not create a reference to that 'module'. There's no such thing as reference to a module. There's only reference to thing(s) exported by a module.

    require('xxx.js'), where the .js extension can be omitted, returns whatever is exported by that xxx.js file. If that xxx.js file exports an object, require('xxx.js') returns an object; if a function is exported, require('xxx.js') returns a function; if a single string is exported, require('xxx.js') returns a string...

    If you check source code of file express.js, you will see that it exports a single function. So in

    var express = require('express')
    

    The first express is assigned whatever is exported by module express, which in this case happens to be a single function. express is a function, not a reference to a module. Hence on second row you just invoke that function:

    var app = express()
    

    Hope this helps!

提交回复
热议问题