In your first example, I'm assuming that app
represents an Express instance from something like this:
const app = express();
If so, then app
is a request handler function that also has properties. You can pass it like this:
var server = http.createServer(app);
because that app
function is specifically designed to be an http request listener which is passed the arguments (req, res)
from an incoming http request as you can see here in the doc.
Or, in Express, you can also do:
const server = app.listen(80);
In that case, it will do the http.createServer(app)
for you and then also call server.listen(port)
and return the new server instance.
When you do this:
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(port);
you are just making your own function that's built to handle an incoming http request instead of using the one that the Express library makes for you.
./app
module exports a callback. This is just like there is no difference betweenconsole.log(123)
andvar x = 123; console.log(x)
. – Sulphurylconsole.log(typeof app)
, you will get'function'
, andconsole.log(app.toString())
, you will get'function(req, res, next) {\n app.handle(req, res, next);\n }'
. When you call Express'express()
, you'll get a function that works as callback for the HTTP server and has a multitude of additional properties such asuse
,set
, etc. – Sulphuryl