We can see that it's not very intuitive or easy to write HTML pages with our current infrastructure. Writing the HTML in the JS code as strings is not fun. We would like to serve the HTML content from the HTML files. We will begin with taking in two modules, which we will need to read from a file (on the disk) in our app
module:
var path = require('path'); var fs = require('fs');
The first one, path
, is the module we use to work with paths, and fs
is the module used to interact with the filesystem. The next step is to get the path to the application's root.
var root = __dirname;
__dirname
is a variable managed by Node.js and has the absolute path to the directory of the Node.js application script. Now, we add the method that will be doing the heavy work of reading the file and sending it to the browser. Add this method to app.js
:
var serveStatic = function(response, file){ var fileToServe = path.join(root, file); var stream = fs.createReadStream(fileToServe); stream.on...