1. Let's start by implementing a simple HTTP server
var http = require ("http"); var server = Http.createserver (function(req, res) { res.writehead ($, {' Content-type ': ' Text/html;charset=utf8 '}); Res.write (' <div style= "font-size:24px;color:red" > one of our simple servers </div> ');}); Server.listen (' 9090 ', ' 127.0.0.1 ');
The results of the above program run as follows:
2. We get the requested URL
var http = require ("http"); var url = require ("url"); var server = Http.createserver (function(req, res) { var req_path = Url.parse (Req.url). path; var str = ' <div style= ' font-size:24px;color:red ' > Our request path is: ' +req_path+ ' </div> '; Res.writehead ($, {' Content-type ': ' Text/html;charset=utf8 '}); Res.write (str);}); Server.listen (' 9090 ', ' 127.0.0.1 ');
The result of the above program is:
3. The directory where the current file is located is the root directory of the Web site, according to the requested URL, the corresponding file is returned to the browser;
varHTTP = require ("http");varurl = require ("url");varFS = require ("FS");varServer = Http.createserver (function(req, res) {varReq_path =Url.parse (req.url). path; varfilepath = __dirname +Req_path; Fs.exists (filepath,function(exists) {if(exists) {Fs.stat (filepath,function(err, stats) {if(Err) {Res.writehead (, {' Content-type ': ' Text/html;charset=utf8 '}); Res.end (' <div styel= ' color:black;font-size:22px; >server error</div> '); }Else{ if(Stats.isfile ()) {varFile =Fs.createreadstream (filepath); Res.writehead ($, {' Content-type ': ' Text/html;charset=utf8 '}); File.pipe (RES); }Else{fs.readdir (filepath,function(err, files) {varstr = "; for(varIinchfiles) {STR+ = Files[i] + ' <br/> '; } res.writehead ($, {' Content-type ': ' Text/html;charset=utf8 '}); Res.write (str); }); } } }); }Else{Res.writehead (404, {' Content-type ': ' Text/html;charset=utf8 '}); Res.end (' <div styel= ' color:black;font-size:22px; >404 not found</div> '); } });}); Server.listen (' 9090 ', ' 127.0.0.1 ');
Nodejs implementation of a simple HTTP static file server (i)