Quick Build Nodejs local server under Windows

Source: Internet
Author: User

Windows under the rapid construction NodeJS Local server



First we will download the corresponding version of the installation package to the node. JS website

http://nodejs.cn/download/



Then the installation, and the installation of common software similar to the next step directly next to it.

We then verify that node is successfully installed, win+r input cmd to bring up the console and enter node-v and npm-v to view the node version and the NPM (Package management tool) version.



Then we'll create a server.js file and paste the following code up

var http = require (' http ');

var fs = require (' FS '); // introducing a file reading module

var documentroot = ' I:/webserver ';

// directory of files that need to be accessed

var server=http.createserver (function (req,res) {

var url = req.url;

// Client-Input URL , for example, if you enter localhost:8888/index.html

// so here's the url = =/index.html

var file =documentroot + URL;

Console.log (URL);

Fs.readfile (file, function (Err,data) {

/*

Err to a file path

Data as a callback function

One parameter of the callback function is the information returned by the read error, and there is no error when returning null

Data to read the text content returned successfully

*/

if (err) {

Res.writeheader (404,{

' Content-type ': ' text/html;charset= ' utf-8 '

});

Res.write ('

Res.end ();

}else{

Res.writeheader (200,{

' Content-type ': ' text/html;charset= ' utf-8 '

});

Res.write (data); // will be index.html displayed on the client

Res.end ();

}

});

}). Listen (8888);

Console.log (' Server open successfully ');

To facilitate the opening of the Server debug Web site, we create a site directory to hold node. js files and Web site files

Then we can start the server from the console.


Browser input http://localhost:8888/index.html

It is so simple, everyone quickly to build their own Nodejs local server it!

Quick Build Nodejs local server under Windows

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.