Build a simple http server for nodejs

Source: Internet
Author: User

Build a simple http server for nodejs

Build a simple nodejs Server

Through some simple configuration, we can build an http server based on nodejs.

How to configure url routing through switch

// This is a simple Node HTTP server that can process files in the current directory // and implement two special URLs for testing // Use HTTP: // localhost: 8000 or http: // 127.0.0.1: 8000 connect to this server // first load all modules required var http = require ('http '); // load the http Service api module var fs = require ('fs'); // load the fs File Service api module var server = new http. server (); // create a new HTTP server var urlapi = require ('url'); // create a url routing api module Server. listen (8000); // listen to port 8000 // use the on method to register event processing. This event has been listened on, and any request will enter the callback function and execute the corresponding server operation. on ('request', function (request, response) {// The URL var url = urlapi that triggers the processing function when there is a request. parse (request. url); // listen to the requested website, and use the current Script directory as the root directory url address console. log (url. pathname); // a special URL allows the server to wait for the switch (url. pathname) {// identify the request path information case ''| '/': // The website root directory for processing the request. It specifies the corresponding folder. The default value is index.html, and nodejs is an efficient stream processing solution, you can also configure fs through the configuration file. readFile (". /page/index.html ", function (err, content) {// open the requested file if (err) {// output error information, you can also customize the error message response. writeHead (404, {'content-type': 'text/plain; charset = "UTF-8" '}); response. write (err. message); response. end ();} else {// response data returned when the request is successful. writeHead (200, {'content-type': 'text/html; charset = UTF-8 '}); // tells the corresponding header file that the returned data Type is response. write (content); // The returned content. Sometimes, the buter data type response is added. end (); // The end response. If it is not written, it will remain in the response state, and content will not be displayed on the page.}); break; case '/test/delay ': // This is used to simulate slow network connections // use the query string to obtain the delay duration, or 2000 ms var delay = parseInt (url. query) | 2000; // set the response status and header response. writeHead (200, {'content-type': 'text/plain; charset = UTF-8 '}); // start writing response body response immediately. write ('sleeping for '+ delay + 'milliseconds... '); // complete the response setTimeout (function () {response. write ('done. '); response. end () ;}, delay); break; case '/test/mirror': // if the request is test/mirror, the original article returns it // response status and header response. writeHead (200, {'content-type': 'text/plain; charset = UTF-8 '}); // write the response body response with the requested Content. write (request. mothod + ''+ request. url + 'HTTP/'+ request. httpVersion + '\ r \ n'); // all request headers for (var h in request. headers) {response. write (h + ':' + request. headers [h] + '\ r \ n');} response. write ('\ r \ n '); // use an extra blank row to end the header. // complete the response in these event handler functions. // when the data block of the request body is complete, write it to the request in the response. on ('data', function (chunk) {response. write (chunk) ;}); // when the request ends, the response also completes the request. on ('end', function (chunk) {response. end () ;}); break; case '/json': // simulate json data return // response status and header response. writeHead (200, {'content-type': 'application/json; charset = UTF-8 '}); response. write (JSON. stringify ({test: 'success'}); response. end (); break; default: // process files from the local directory, mainly static resource files, static server construction and other methods var filename = url. pathname. substring (1); // remove the prefix '/'var type = getType (filename. substring (filename. lastIndexOf ('. ') + 1); console. log (filename); // get the file type css js .... // asynchronously read the file and pass the content as a separate data module to the callback function. // For a really large file, use the stream API fs. createReadStream () is better than fs. readFile (filename, function (err, content) {if (err) {response. writeHead (404, {'content-type': 'text/plain; charset = "UTF-8" '}); response. write (err. message); response. end ();} else {response. writeHead (200, {'content-type': Type}); response. write (content); response. end () ;}}); break ;}}); // a function getType (endTag) {var type = null is defined here; switch (endTag) {case 'html': type = 'text/html; charset = UTF-8 '; break; case 'htm': type = 'text/html; charset = UTF-8 '; break; case 'js': type = 'application/javascript; charset = "UTF-8"'; break; case 'css ': type = 'text/css; charset = "UTF-8" '; break; case 'txt': type = 'text/plain; charset = "UTF-8" '; break; case 'manifest ': type = 'text/cache-manifest; charset = "UTF-8" '; break; default: type = 'application/octet-stream'; break;} return type ;}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.