Node. js notes-do not use the page template to render the interface
This is because you cannot remember any name.
Looking at online references, the ejs party and jade party trend is like the fire Σ (° △° |) quit )︴
However, it is not good for me to wait for a newbie to get rid of the template engine and concentrate on html.
--------------------------
This article refers to the second chapter of Node. js practice. The source code is appended to the end.
First, check the core code to read html files from the cache or hard disk:
Function serveStatic (response, cache, absPath) {if (cache [absPath]) {// check whether the file is in the cache sendFile (response, absPath, cache [absPath]); // returned file from memory} else {fs. exists (absPath, function (exists) {// check whether the object exists if (exists) {fs. readFile (absPath, function (err, data) {// returns the file from the hard disk if (err) {send404 (response);} else {cache [absPath] = data; // Add sendFile (response, absPath, data) to the cache; // read the file and return});} else {send404 (response );}});}}
Send404 and sendFile Functions
function send404(response) { response.writeHead(404, {'Content-Type': 'text/plain'}); response.write('Error 404: resource not found.'); response.end();}function sendFile(response, filePath, fileContents) { response.writeHead( 200, {"content-type": mime.lookup(path.basename(filePath))} ); response.end(fileContents);}
Next, create a server.
var server = http.createServer(function(request, response) { var filePath = false; if (request.url == '/') { filePath = 'public/index2.html'; } else { filePath = 'public' + request.url; } var absPath = './' + filePath; serveStatic(response, cache, absPath);});
Run it. It should be a blog post from csdn.
Http://pan.baidu.com/s/1bnvYkSB