Reputation: 95
Can something explain how in res.write(html)
, the html parameter maps to ./index.html
?
Here is the code. Am I not understanding how callback functions work?
var http = require('http');
var fs = require('fs');
var host = 'localhost';
var port = '8888';
fs.readFile('./index.html', function(err, html){
if(err){
console.log(err);
return;
}
var server = http.createServer(function(req, res){
res.StatusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.write(html);
res.end();
});
server.listen(port, host, function(){
console.log('Server running on port ' + port);
})
});
Upvotes: 0
Views: 47
Reputation: 707148
This code says to run fs.readFile('./index.html', ...)
to get the file './index.html' into memory. When the file is done being read into memory, call the callback that you passed it and put the contents into the function parameter you named html
. At any point inside that callback function, you can refer to the html
function parameter and it will contain the contents of the './index.html' file that was read from disk.
Then after that, create your server and define a request handler callback for it that will be called each time an incoming request is received by your web server.
That callback will then send the data in that html
parameter as the response to that incoming request.
Then, start that server.
It's kind of an odd way to write things, but there's nothing technically wrong with it.
Note that the http.serverServer()
callback is nested inside the other callback. In Javascript, you have access to not only your own local parameters and local variables, but also the parameters and local variables of any parent functions that you are nested inside of.
Am I not understanding how callback functions work?
I don't know what you do and don't understand about callback functions. In both the fs.readFile()
and http.createServer()
case, these are callbacks that will be called sometime in the future when some operation completes. In the fs.readFile()
case, it's callback is called when the file contents have been entirely read into memory. In the http.createserver()
case, the callback is called whenever any incoming request is received by the web server.
Upvotes: 1