Set up a local http server using nodejs

Source: Internet
Author: User

Because I don't do php-related things, I am too lazy to install apache. I simply use nodejs to build a local server for testing.

Nodejs is a powerful tool for frontend intervention. Moreover, nodejs is becoming more and more commercially available.

Nodejs is actually very underlying. In terms of functionality, it is both apache and php. Functions such as building an http server are originally encapsulated by apache, but nodejs needs to be built manually. In practice, we can use a ready-made framework. But here, I want to build it manually and deepen my understanding of the http server.

We run the following file on node. I name it http. js. It will create an httpServer and listen to port 3000.

var PORT = 3000;var http = require('http');var url=require('url');var fs=require('fs');var mine=require('./mine').types;var path=require('path');var server = http.createServer(function (request, response) {    var pathname = url.parse(request.url).pathname;    var realPath = path.join("assets", pathname);    //console.log(realPath);    var ext = path.extname(realPath);    ext = ext ? ext.slice(1) : 'unknown';    fs.exists(realPath, function (exists) {        if (!exists) {            response.writeHead(404, {                'Content-Type': 'text/plain'            });            response.write("This request URL " + pathname + " was not found on this server.");            response.end();        } else {            fs.readFile(realPath, "binary", function (err, file) {                if (err) {                    response.writeHead(500, {                        'Content-Type': 'text/plain'                    });                    response.end(err);                } else {                    var contentType = mine[ext] || "text/plain";                    response.writeHead(200, {                        'Content-Type': contentType                    });                    response.write(file, "binary");                    response.end();                }            });        }    });});server.listen(PORT);console.log("Server runing at port: " + PORT + ".");

We also introduced a mine. js file, which is written by myself. It stores name-value pairs and defines the return method for objects with different suffixes:

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"};

The fs module is used to read files and provides methods to read files. In fact, if you carefully study the document, you will find that it has two reading methods: synchronous and asynchronous. Fs. exists: many articles on the Internet write path. exists. We recommend writing fs. exists. Otherwise, an alarm is reported:

It should be noted that not only does the browser access html files, but external files such as js and css linked in them also form an http access. Therefore, the http. createServer callback is actually executed multiple times in one page access. We can see the following in console. log (realPath:

 

There is no function for adding ingress index.html, so the access address should be full of http: // 127.0.0.1: 3000/index.html

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.