Node. js notes-do not use the page template to render the interface

Source: Internet
Author: User
Tags sendfile

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.