Linux uses node. js to establish a service instance that accesses static Web pages

Source: Internet
Author: User
Tags node server

Linux uses node. js to establish a service instance that accesses static Web pages
First, install the environment that node. js needs to run.
Second, create the node directory (/NODE/WWW) and create the node. JS Service file under the directory Server.js

var http = require (' http ');

var fs = require (' FS ');//introduction of file reading module

var documentroot = '/node/www ';//directory of files to be accessed

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

var url = req.url;
The URL entered by the client, for example, if the input localhost:9999/index.html
So here's the URL = =/index.html

var file = documentroot + URL;
Console.log (URL);//node/www/index.html

/*
File path
function is a callback,
The Err of function is the information returned by the read error, and there is no error when returning NULL
function data for reading the text content returned successfully
*/
Fs.readfile (file, function (Err,data) {
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);//display index.html on the client
Res.end ();
}

});

}). Listen (9999);

Console.log (' Server open successfully ... ');
Third, create index.html home file, put the path to/node/www/below
Four, start the Service command: node Server.js
Five, browser input address: http://localhost:9999/index.html

Linux uses node. js to establish a service instance that accesses static Web pages

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.