Use Nodejs to build a simple service listener

Source: Internet
Author: User
Tags configuration settings log log

As a practitioner for about three years, and engaged in a half-year PHP development work of the front end, for the backstage, especially for the development of JS language Nodejs, that is more interested in, although itself has not contacted the relevant work, but only privately do a little experiment, But the record is convenient to review later!

Today the main record, a long time ago with Nodejs to make a simple service listener procedures!

As we all know, through the Nodejs can listen to the front desk request, here is an official website of the Hello World example:

var http = require (' http '); Http.createserver (function (req, res) {  Res.writehead ($, {' Content-type ': ' Text/plain '});  Res.end (' Hello world\n ');}). Listen (1337, ' 127.0.0.1 '); Console.log (' Server running at http://127.0.0.1:1337/');

The above code is believed to know node's child shoes should be more familiar!

Now that node can listen for requests, is it possible to return different files or content based on different requests from the foreground? This is not a simple server! Holding this idea, a simple experiment, we all know that the server can be different depending on the requested file, will use the corresponding mine type! Like what.. The type of mine used by/INDEX.CSS is text/css! So, should we have a simple configuration of a common mine type? Here, do a simple mine configuration file Mine.js, with JSON to store a common format:

Exports.types = {  "css": "Text/css",  "gif": "Image/gif",  "html": "Text/html",  "ico": "Image/x-icon",  "JPEG": "Image/jpeg", "  jpg": "Image/jpeg",  "JS": "Text/javascript",  "JSON": "Application/json",  "PDF": "Application/pdf",  "png": "Image/png",  "svg": "Image/svg+xml",  "swf": "application/ X-shockwave-flash ",  " TIFF ":" Image/tiff ",  " TXT ":" Text/plain ",  " wav ":" Audio/x-wav ",  " WMA ":" Audio/x-ms-wma ",  " wmv ":" Video/x-ms-wmv ",  " xml ":" Text/xml "};

Of course, there are many other formats besides these, and there are no examples here!

Well, with the mine format corresponding file configuration file, the next simple, first of all, according to the official website example to build a listener, and then in the listener to add a simple www.baidu.com/this kind of link default open file processing, as well as relative link to the complement! Of course, you have to do a simple error handling, such as 404,500! See the code specifically:

/* Build an HTTP server, listen for HTTP requests */var HTTP = require ("http"), FS = require (' FS '), PATH = require (' path '), mine = require ('./mine '). Ty  Pes;url = require (' URL ');//define simple tool//Get current time var date = function (ms) {var date = ms? New Date (ms): new Date (), Mon = Date.getmonth () >= 10 + 1? '-': '-0 ', d = date.getdate () >= 10? '-': '-0 ', hour = date.gethours () >= 10? ': ' 0 ', min = date.getminutes () >= 10? ': ': ': 0 ', sec = Date.getseconds () >= 10?    ': ': ': 0 '; return date.getfullyear () + Mon + (date.getmonth () + 1) + D + date.getdate () + hour + date.gethours () + min + Date.getminu    TES () + sec + date.getseconds ();},//defines the output log log method, with time, convenient debugging Debuglog = function (mes) {var now = date (); Console.log (now + "" + mes);};/ /Service Listener Exports.server = function () {Http.createserver (function (req, res) {var pathname = Url.parse (req.url). Pathname ,//Get the filename in the URL pathname = (pathname!== "/" && pathname)? Pathname: "/index.html";//handling links with '/' end of case var Realpath =Path.join ("..        /", Path.normalize (Pathname.replace (/\.\./g," ")),//Convert link to physical path ext = path.extname (Realpath); Ext = ext? Ext.slice (1): ' unknown ';//Get File name extension//Find file Fs.exists (Realpath, function (exists) {if (!exists) {/                /processing 404 Res.writehead (404, {' Content-type ': ' Text/plain '});                Res.write ("This request URL" + pathname + "is not found on the this server.");            Res.end (); } else {//Read file Fs.readfile (Realpath, "binary", function (err, file) {if (err) {//Program error 5                        00 Error res.writehead, {' Content-type ': ' Text/plain '                        });                    Res.end (ERR); } else {//normal return file var ContentType = Mine[ext] | | "Text/plain", or//According to the configuration settings in the mine.js corresponding to the ContentType Res.writehead (, {' Conte Nt-type ': ContentType});                        Res.write (file, "binary");                    Res.end ();                  }                });    }        });    }). Listen (8888, ' localhost '); Tool. Debuglog ("HTTP service started, start listening for 127.0.0.1:8888 HTTP request!") ");}

OK, the code here is basically the end, of course, this is only the simplest function, we can enrich their own! This article is here, welcome you to exchange discussions!

Use Nodejs to build a simple service listener

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.