Serving files with Node.js
Node.js differs from the usual Linux-Apache-MySQL-PHP setup. We have to write the server that handles the incoming request. When the user requires an image from our backend, Node.js doesn't serve it automatically. The very first file of our social network will be server.js
with the following content:
var http = require('http'); var fs = require('fs'); var path = require('path'); var files = {}; var port = 9000; var host = '127.0.0.1'; var assets = function(req, res) { // ... }; var app = http.createServer(assets).listen(port, host); console.log("Listening on " + host + ":" + port);
We require three native modules that we will use to drive the server and deliver assets. The last two lines of the preceding code run the server and print a message to the console.
For now, the entry point of our application is the assets
function. The main purpose of this method is to read files from the hard disk and serve it to the users. We will use req.url
to fetch the current...