node. JS Learning Note 01 For beginners to build a static server

Source: Internet
Author: User
Tags sendfile

I hope this article will solve your problem: "I now know some of the basic concepts of node. js, how to set up a static server?" ”

Please refer to the first two articles of the blogger:

A completely beginner-oriented node. JS Guide

The module System of node. js and some common module

The effect of this article (style is not done, everyone will be next):

All of the code listed is available for testing, so rest assured.

What is static server?

Static server, with it, you can let external access to our static Web page. In the function: it can send files to the user (such as: HTML, CSS, JS, etc.). As the previous article said:

node. JS is not itself a iis,apache-like webserver, it's a JavaScript run environment . So, we need to encode in order to achieve a real Beijing server.

File stucture

The background directory is established as follows, more general. You can arbitrarily define the directory structure, the code on the corresponding place to change it.

App.js

The focus of this article is on the next server module, which does not introduce the code in App.js. (The main line code written in the App.js is an unwritten convention, no need to abide by, casual, casual ...) )

varHTTP = require (' http ');varPath = require (' path ');//introducing our own server modulevarServer = require ('./server.js ')); Http.createserver (function(Request, response) {//The following judgments are used to make simple routing    if(Request.url = = "/") {FilePath= Path.join (__dirname, '/public/index.html ')); } Else{FilePath= Path.join (__dirname, '/public ' +Request.url); } server.servestatic (response, FilePath);}). Listen (/*listening on port 4000*/4000,function() {Console.log ("Server listening on port 4000");});

Mime

A static server has a function that must be implemented to specify the MIME type in an HTTP message. WIKI MIME

We will refer to a third-party component mime, installed through NPM, which can map MIME type according to the extension name of the file.

So, run NPM install MIME--save in the root directory

Server.js

varFS = require (' FS ');//provide the ability to derive a MIME type based on the filename extensionvarMIME = require (' MIME '));varCache = {};//This is not iis,apache so 404 must be customized,functionsend404 (response) {Response.writehead ($, {"Content-type": "Text/html" }); Response.Write ("); Response.End ();}//send a file to the clientfunctionsendFile (response, FilePath, filecontents) {Response.writehead ($, {"Content-type": Mime.lookup (FilePath)}); Response.End (filecontents);}//This function is exported to the main module using thefunctionservestatic (response, Abspath) {if(Cache[abspath]) {sendFile (response, Abspath, Cache[abspath]); } Else{fs.exists (Abspath,function(exists) {if(exists) {fs.readfile (Abspath,function(err, data) {if(Err) {send404 (response); } Else{Cache[abspath]=data;                    SendFile (response, Abspath, data);            }                }); }            Else{send404 (response);    }        }); }}exports.servestatic= Servestatic;

Explanation section as comments ... At this point, the coding section is finished.

How to test we can devolve a index.html content in./public free ... When node runs up, as long as the input http://localhost:4000 returns it, the input Http://localhost:4000/XXX returns 404, then the static server is set up.

Summary

This demo is too simple and should not satisfy everyone's appetite. The next article will show you how to build a dynamic website (for example, a restful service).

node. JS Learning Note 01 For beginners to build a static server

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.