NodeJs Creating a Web server

Source: Internet
Author: User

The following is a demonstration of one of the most basic HTTP server architectures (using 8081 ports) to create the Ser.js file, as shown in the code below:

var http = require (' http '); var fs = require (' FS '); var url = require (' URL ');//Create server = Http.createserver (function (req , res) {//Resolve request, including file name Var pathname=url.parse (req.url). pathname;//the file name of the output request Console.log ("Request for" +pathname+ " Received. "); /Read the requested file contents from the file System Fs.readfile (PATHNAME.SUBSTR (1), function (Err,data) {if (err) {Console.log (err);//http Status Code 404:not Found//content type:text/htmlres.writehead (404,{' content-type ': ' text/html '});} Else{//http Status Code 200:ok//content type:text/htmlres.writehead (200,{' content_type ': ' text/html '});//Response File Contents Res.write ( Data.tostring ());} Send response data Res.end ();}); /Monitor 8000 port Server.listen (8000);//console Print information Console.log ("Server running on http://127.0.0.1:8000 ...");

  

Next we create a index.htm file in this directory with the following code:

Execute the ser.js file:

E:\nodejs>node Serserver running on http://127.0.0.1:8000

  

NodeJs Creating a Web 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.