Complete static server-node. js Touch Stone Series 4

Source: Internet
Author: User
Tags pkcs12 pkcs7 rfc822 gtar
Document directory
  •  
  • I. Exploration of an error
  • Ii. Read and Write files
  • 3. Analyze the Request Path
  • Iv. Mime
  • 5. Complete
Series Directory: node. js Touch Stone series directory 1. Exploration caused by an error

The last time we obtained the 'user-agent' attribute of the headers attribute of the request object, I used the request. headers. thanks for the reminder from artwl, the User-Agent syntax cannot be used to write experiments. But why not? I am confused about this. Objects in JS can be understood as a set of attributes. The composition of attributes is a key-value pair, and functions are not specialized. They are treated like other types. The attribute value can be accessed through object. Key or object ['key. Where is the problem? It was fruitless to get online. Then observe the headers object:

headers:   { host: 'localhost:888',     connection: 'keep-alive',     'cache-control': 'max-age=0',     'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1 CoolNovoChromePlus/1.6.4.30',     accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',     'accept-encoding': 'gzip,deflate,sdch',     'accept-language': 'zh-CN,zh;q=0.8',     'accept-charset': 'GBK,utf-8;q=0.7,*;q=0.3' }

We found that all the keys with quotation marks all have '-'. It turns out to be a bad horizontal bar.

Reminder:If the key name contains '-', spaces, and other seemingly invalid characters, JS is very tolerant, but you must enclose it in quotation marks. During access, you cannot obtain the value by using the dot and key names. You need to enclose the value in square brackets.

The two statements can be clearly said for a long time. What I want to say is that it is normal for a small stone to let us get stuck, touch him, and exclude him.

In addition, if you want to touch an object, you can print it out in the repl environment. For example, for the HTTP module we introduced earlier, you can enter:

D:>Node

>Require ('http ')

You will get:

You don't need to check the documentation for the status code?

Ii. Read and Write files

To complete the task of setting up a static server, we need file I/O. node. js has a built-in FS module, so that we can read and write files. To organize a directory, follow these steps:

Myhttpserver

| _____ App. js

| _____ Webroot

| _____ Index.htm

 

Here, the webroot folder is the home of our static page. We hope that we will be able to access the page from the client if we lose it in the future. You can paste a few lines in the index.htm file. Later we will read them from the file and display them in the console and send them to the browser.

Before writing code, we first use the previous method to view the FS module:

There are so many methods in FS. Now it's time for us to read the document. Go to the official website and find fs. readfile? OK. Use it. The code for testing this method will not be written separately. We recommend that you first write the code and run it in small steps. It is a good method for learning and also applicable to programming, in this way, you can avoid the difficulty of locating the problem scope when you encounter problems, and you can continue to give yourself a small encouragement. Directly run the Code:

/* Read a file and put to user agent */var HTTP = require ('http'), FS = require ('fs'); http. createserver (function (request, response) {// read the file and write it to response. The file name is hardcoded var Path = _ dirname + '/webroot/index.htm'; FS. readfile (path, 'utf-8', function (ERR, data) {// read the content in data // print it on the console // console. log (PATH); console. log (data); response. end (data );});}). listen (888); console. log ('server start at Port 888. ');

 

The above code has a global attribute _ dirname, which indicates the directory where the code is currently running. The document was written in black and white. Hmm? Why is there such a line:__dirnameIsn' t actually a global but rather local to each module. It's just a mistake. It's relative to every module. In addition, please note that there are two underscores. _ D I R n a m e.

3. Analyze the Request Path

In the previous section, we implemented the process of reading text files and sending them to the client browser. However, the Read File name is hard-coded in the code. Now, we need the user to specify what files he needs, and then read them and send them to them. The user-specified path and file name information, as we mentioned earlier, is passed through the request, you must remember in Series 3, we once printed the request in the server background, and one of the many attributes of the request is the URL attribute. Yes, we usually map the file path through URLs. However, in the current MVC and rest era, the situation has become somewhat complicated and will not be mentioned for the time being. Next we will speed up the process. I will gradually move some explanations to the comments of the Code. Therefore, read the code. Er, before reading the code, a URL can be divided into host addresses, paths, and key-value pairs. You know this. Well, if you don't think it's awkward, please do the following:

 

We try to introduce the URL module and use this tool to parse a series of examples to get an object. Here, pathname is what we need, but now we need to map it to the absolute address of our server. Now, let's try:

 

/* Map the URL path to serverpath */var HTTP = require ('http'), FS = require ('fs'), urlutil = require ('url '); // node. the JS recommendation variable name is the same as the module name. To avoid misunderstanding, change HTTP temporarily. createserver (function (request, response) {var Path = urlutil. parse (request. URL ). pathname; console. log (PATH); // map local var abspath = _ dirname + "/webroot" + path; console. log ("path at server:" + abspath );}). listen (888); console. log ('server start in Port 888. ');

 

Complete the task. Now we have to send the file to the browser.

var http = require('http'),fs = require('fs'),urlutil = require('url'),path = require('path');http.createServer(function(request, response){//get path from request's urlvar urlpath = urlutil.parse(request.url).pathname;//map the path to server pathvar absPath = __dirname + "/webroot" + urlpath;//test whether the file is exists firstpath.exists(absPath, function(exists) {if(exists) {//if okfs.readFile(absPath,function(err, data) {//our work is hereif(err) throw err;console.log(data);response.write(data);response.end();});} else {//show 404response.end('404 File not found.');}});}).listen(888);console.log('Server start in port 888.');

Well, the Code perfectly implements our tasks. Of course, there are some minor issues that need to be improved. But let's take a rest and find some adjectives to praise yourself. Don't be so stingy with yourself. No one will hear you, isn't it?

Iv. Mime

The above Code also lacks the ability to read text files, and the console prompts are messy and unclear. One by one.

First, complete the console. You only need to specify the encoding when reading the file, for example, readfile (abspath, 'utf-8', function (... You can.

The rest is about reading and writing different format files. In order to tell the browser what type of file we send to him, we need to write the header information to response and then send it to the browser. The browser determines the type of content sent based on the information. This information is still a key-value pair, and the key is Content-Type. As the name suggests, it is the content type. What is the value? As we all know, because the servers and browsers are developed by different developers, we need to communicate well. Otherwise, if you say that the file type is text and he understands it as an image, isn't it a problem?

To avoid this trouble, it is mime. For more information about mime, see here. What we need to do is to get the list on this page and put it into our own code. For clarity, drop it into a module. The module name is mime. Naturally, we want to use an object to represent this list.

exports.types = {'323':'text/h323',acx:'application/internet-property-stream',ai:'application/postscript',aif:'audio/x-aiff',aifc:'audio/x-aiff',aiff:'audio/x-aiff',asf:'video/x-ms-asf',asr:'video/x-ms-asf',asx:'video/x-ms-asf',au:'audio/basic',avi:'video/x-msvideo',axs:'application/olescript',bas:'text/plain',bcpio:'application/x-bcpio',bin:'application/octet-stream',bmp:'image/bmp',c:'text/plain',cat:'application/vnd.ms-pkiseccat',cdf:'application/x-cdf',cer:'application/x-x509-ca-cert','class':'application/octet-stream',clp:'application/x-msclip',cmx:'image/x-cmx',cod:'image/cis-cod',cpio:'application/x-cpio',crd:'application/x-mscardfile',crl:'application/pkix-crl',crt:'application/x-x509-ca-cert',csh:'application/x-csh',css:'text/css',dcr:'application/x-director',der:'application/x-x509-ca-cert',dir:'application/x-director',dll:'application/x-msdownload',dms:'application/octet-stream',doc:'application/msword',dot:'application/msword',dvi:'application/x-dvi',dxr:'application/x-director',eps:'application/postscript',etx:'text/x-setext',evy:'application/envoy',exe:'application/octet-stream',fif:'application/fractals',flr:'x-world/x-vrml',gif:'image/gif',gtar:'application/x-gtar',gz:'application/x-gzip',h:'text/plain',hdf:'application/x-hdf',hlp:'application/winhlp',hqx:'application/mac-binhex40',hta:'application/hta',htc:'text/x-component',htm:'text/html',html:'text/html',htt:'text/webviewhtml',ico:'image/x-icon',ief:'image/ief',iii:'application/x-iphone',ins:'application/x-internet-signup',isp:'application/x-internet-signup',jfif:'image/pipeg',jpe:'image/jpeg',jpeg:'image/jpeg',jpg:'image/jpeg',js:'application/x-javascript',latex:'application/x-latex',lha:'application/octet-stream',lsf:'video/x-la-asf',lsx:'video/x-la-asf',lzh:'application/octet-stream',m13:'application/x-msmediaview',m14:'application/x-msmediaview',m3u:'audio/x-mpegurl',man:'application/x-troff-man',mdb:'application/x-msaccess',me:'application/x-troff-me',mht:'message/rfc822',mhtml:'message/rfc822',mid:'audio/mid',mny:'application/x-msmoney',mov:'video/quicktime',movie:'video/x-sgi-movie',mp2:'video/mpeg',mp3:'audio/mpeg',mpa:'video/mpeg',mpe:'video/mpeg',mpeg:'video/mpeg',mpg:'video/mpeg',mpp:'application/vnd.ms-project',mpv2:'video/mpeg',ms:'application/x-troff-ms',mvb:'application/x-msmediaview',nws:'message/rfc822',oda:'application/oda',p10:'application/pkcs10',p12:'application/x-pkcs12',p7b:'application/x-pkcs7-certificates',p7c:'application/x-pkcs7-mime',p7m:'application/x-pkcs7-mime',p7r:'application/x-pkcs7-certreqresp',p7s:'application/x-pkcs7-signature',pbm:'image/x-portable-bitmap',pdf:'application/pdf',pfx:'application/x-pkcs12',pgm:'image/x-portable-graymap',pko:'application/ynd.ms-pkipko',pma:'application/x-perfmon',pmc:'application/x-perfmon',pml:'application/x-perfmon',pmr:'application/x-perfmon',pmw:'application/x-perfmon',pnm:'image/x-portable-anymap',pot:'application/vnd.ms-powerpoint',ppm:'image/x-portable-pixmap',pps:'application/vnd.ms-powerpoint',ppt:'application/vnd.ms-powerpoint',prf:'application/pics-rules',ps:'application/postscript',pub:'application/x-mspublisher',qt:'video/quicktime',ra:'audio/x-pn-realaudio',ram:'audio/x-pn-realaudio',ras:'image/x-cmu-raster',rgb:'image/x-rgb',rmi:'audio/mid',roff:'application/x-troff',rtf:'application/rtf',rtx:'text/richtext',scd:'application/x-msschedule',sct:'text/scriptlet',setpay:'application/set-payment-initiation',setreg:'application/set-registration-initiation',sh:'application/x-sh',shar:'application/x-shar',sit:'application/x-stuffit',snd:'audio/basic',spc:'application/x-pkcs7-certificates',spl:'application/futuresplash',src:'application/x-wais-source',sst:'application/vnd.ms-pkicertstore',stl:'application/vnd.ms-pkistl',stm:'text/html',svg:'image/svg+xml',sv4cpio:'application/x-sv4cpio',sv4crc:'application/x-sv4crc',swf:'application/x-shockwave-flash',t:'application/x-troff',tar:'application/x-tar',tcl:'application/x-tcl',tex:'application/x-tex',texi:'application/x-texinfo',texinfo:'application/x-texinfo',tgz:'application/x-compressed',tif:'image/tiff',tiff:'image/tiff',tr:'application/x-troff',trm:'application/x-msterminal',tsv:'text/tab-separated-values',txt:'text/plain',uls:'text/iuls',ustar:'application/x-ustar',vcf:'text/x-vcard',vrml:'x-world/x-vrml',wav:'audio/x-wav',wcm:'application/vnd.ms-works',wdb:'application/vnd.ms-works',wks:'application/vnd.ms-works',wmf:'application/x-msmetafile',wps:'application/vnd.ms-works',wri:'application/x-mswrite',wrl:'x-world/x-vrml',wrz:'x-world/x-vrml',xaf:'x-world/x-vrml',xbm:'image/x-xbitmap',xla:'application/vnd.ms-excel',xlc:'application/vnd.ms-excel',xlm:'application/vnd.ms-excel',xls:'application/vnd.ms-excel',xlt:'application/vnd.ms-excel',xlw:'application/vnd.ms-excel',xof:'x-world/x-vrml',xpm:'image/x-xpixmap',xwd:'image/x-xwindowdump',z:'application/x-compress',zip:'application/zip'}

 

There are many types, so it is very long, but the structure is very simple. Note that in the module, you can link the Dongdong chain to be exposed to exports. Save this file as mime. js. We can use it later.

VaR mime = require ('./MIME ')

This syntax is used for access.

Everything is ready, and it is only one step away from victory.

5. Complete

Complete code:

/* Final server */var HTTP = require ('http'), FS = require ('fs'), urlutil = require ('url '), path = require ('path'), mime = require ('. /MIME '); http. createserver (function (request, response) {// get path from request's urlvar urlpath = urlutil. parse (request. URL ). pathname; // map the path to server pathvar abspath = _ dirname + "/webroot" + urlpath; // test whether the file is exists firstpath. exists (abspath, fun Ction (exists) {If (exists) {// Read File FS in binary mode. readfile (abspath, 'binary ', function (ERR, data) {// our work is hereif (ERR) Throw err; // obtain the appropriate MIME type and write the response header information var ext = path. extname (urlpath); Ext = ext? Ext. slice (1): 'unknown '; console. log (EXT); var contenttype = mime. types [ext] | "text/plain"; console. log (contenttype); response. writehead (200, {'content-type': contenttype}); // console. log (data); // write Response in binary mode. write (data, 'binary '); response. end () ;}) ;}else {// show 404response. end ('2014 file not found. ');}});}). listen (888); console. log ('server start in Port 888. ');

Suddenly, we realized the basic functions of Apache and IIS. Okay, you can wash your bed. Good night, big guy.

I almost forgot. Next time we will enter the chat room.

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.