I. Overview
In the previous article, we can use the MIME type module and the file transfer module to return any type of file for the client, but only the static html,css and other files can be returned, while the server-side language such as JSP can be <%%> tag to realize the expansion of Java. According to the request to specify the HTML returned to the client, so that only need to have an HTML template, you can return countless HTML pages, instead of one page to write, and then route the individual HTML according to the request.
Today, we are going to implement an HTML template file like JSP (of course, far from being as powerful as a JSP). First, you'll need to introduce JSON (JavaScript Object Notation)
Second, JSON
JSON is a lightweight data interchange format that can be used instead of XML as the data Interchange format between the server and the client. The program parses the JSON data very quickly. The following is a JSON syntax and an example:
- Data in name/value pairs
- Data is separated by commas
- Curly braces Save Object
- Square brackets Save Array
Example:
{ "Menu":{ "ID":"File", "value":"File", "Popup":{"MenuItem": [{"value": "New", "onclick":
"Createnewdoc ()"
}, {"value": "Open", "onclick": "Open Doc () " }, {"value": " Close ","onclick": " Closedoc () " } ] } }}
From the syntax and examples we can see that JSON has two structures, an object (using {}) and an array (using [])
JSON is based on a subset of JavaScript standards, so JavaScript-based node. JS uses JSON to be unique.
Third, the development process
The project is still a continuation of the previous article of the Testframe, but will not be very involved, mainly about the implementation of the method
1. Create Data folder and Data.json
First, let's identify the data that will be displayed. As before, today's show is also the Tang poetry, JSON data are as follows:
{ "Jingyesi":{"title": "Silent Night Thinking", "1":"moon light Before Bed", "2":"Doubt is the light of the Earth", "3":"Jutou look at the moon", "4":"Think Home" }, "Chunxiao":{"title": "Dawn""1":"Spring sleep does not feel Xiao", "2":"everywhere smell bird", "3":"Night Come wind and Rain", "4":"How much does the flower fall Know" }}
Only for example, so there are only two first.
2. Create a tangshi.html template
Here is a template for creating an HTML tang poem:
<! DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Tang poetry</title> <linkhref="./stylesheets/index.css" rel="stylesheet" Type="Text/css"> </head><body><nav>%title%</nav><div id="value"> <p>%1%</P> <p>%2%</P> <p>%3%</P> <p>%4%</P></div></body></html>
The existing file directory structure is as follows:
The red box is the newly added files and folders.
3. Create Render.js template render function
After we have the template, we will create the new HTML based on the data and the template, then return the HTML file to the client, and here is the render function (which we made into a module):
Render.js
/** * Created by Administrator on 2015/4/1. * *//File modulevarFS =require(' FS ');//Get MIME modulevarMIME =require("MIME");//Get response modulevarResponse =require("./response");varRender = function(res,filepath,datasource,target){ //Read files for renderingFs.readfile (FilePath, function(err,data){ if(ERR) {Console.log (ERR); }Else{varTargetdata = Datasource[target];//Convert HTML templates, generate new HTML vardatastring = Data.tostring (); datastring = Datastring.replace ("%title%", targetdata["title"]); datastring = Datastring.replace ("%1%", targetdata["1"]); datastring = Datastring.replace ("%2%", targetdata["2"]); datastring = Datastring.replace ("%3%", targetdata["3"]); datastring = Datastring.replace ("%4%", targetdata["4"]); Response.response (res,filepath,datastring); } });}; Exports.render = render;
The render function parameter description:
Res:response, for the response client, this parameter is passed to the response module
Path to the filepath:html template
Data sources for Datasource:json files
Target: The name of Tang poetry (e.g. Chunxiao)
Here, there is also a response module, which is to try not to change the previous code, so for the render module to write a separate response module, the code is as follows:
Response.js
/** * Created by Administrator on 2015/4/1. *///获取mime模块var mime = require("mime");var response = function(res,filePath,data){ res.writeHead(200,{ //响应客户端,将文件内容发回去 ‘Content-type‘:mime.lookup(filePath)}); //通过后缀名指定mime类型 res.end(data);};exports.response = response;
4. Use Render
Here to modify the Luyou.js
First, at the beginning of the file, add:
//获取render模块var=require("./file/render");//模板路径var="./file/tangshi.html";//数据源路径vardata="./data/data.json";
Then there is the modification of the HTTP server file routing function,
//Create an HTTP servervarServer = Http.createserver ( function(req,res){Console.log (Req.url);//Print requests in console //Judging URLs, providing different routes if(Req.url = ='/index '|| Req.url = ='/') {//HomeIndex.index (RES); }Else if(Req.url.substr (0,8) =='/tangshi '&& Req.url.indexOf (".") <=0) {//Get the name of the poem varName = Req.url.substr (9);//Get/tangshi/after the string, that is, the name of the poem //Read JSON file contentsFs.readfile (data, function(err,data){ if(ERR) {Console.log (ERR); }Else{Console.log (name);vardatastring = Data.tostring ();varDatajson =JSON. Parse (datastring); Console.log (Datajson);if(!datajson[name]) {//If no poem exists, skip to 404 errorerror404 (RES);return; } render.render (Res,ts,datajson,name); } }); }Else{//Access other static files, such as/stylesheets/index.cssReq.url = Req.url.replace ("/tangshi",""); Response (Res,"./file"+req.url); }});
Client query the path of Tang poetry has two:
Http://localhost:3000/tangshi/jingyesi
Http://localhost:3000/tangshi/chunxiao
The URL is then processed in the/tangshi path, and the name of the poem is extracted for render processing, as for Req.url.indexOf (".") <=0 is designed to prevent static CSS files from being processed in this routing path as well.
"Node. js" (vi) implements HTML templates like JSP tags