First of all thanks to the following code provider Youyudehexie Thank you very much! Let me have the opportunity to study!
varHTTP = require (' http ');varurl = require (' URL '));varFS = require (' FS ');varUtil = require (' util '));varMimeType = { ' txt ': ' Text/plain ', ' HTML ': ' text/html ', ' CSS ': ' Text/css ', ' xml ': ' Application/xml ', ' JSON ': ' Application/json ', ' JS ': ' Application/javascript ', ' jpg ': ' Image/jpeg ', ' JPEG ': ' Image/jpeg ', ' gif ': ' Image/gif ', ' PNG ': ' Image/png ', ' SVG ': ' Image/svg+xml '}varpage_404 =function(req, res, path) {Res.writehead (50U, { ' Content-type ': ' text/html ' }); Res.write (' <!doctype html>\n '); Res.write (' <title>404 not found</title>\n '); Res.write (' ); Res.write (' <p>the requested URL ' +Path+ ' is not found in this server.</p> ' ); Res.end ();}varpage_500 =function(req, res, error) {Res.writehead (500, { ' Content-type ': ' text/html ' }); Res.write (' <!doctype html>\n '); Res.write (' <title>internal Server error</title>\n '); Res.write (' ); Res.write (' <pre> ' + util.inspect (Error) + ' </pre> ');} Http.createserver (function(req, res) {//returns the URL value following the URL port number //For example: http://localhost:1337/a.html is/a.html varpathname =Url.parse (req.url). Pathname; //__dirname Returns the physical path of the Web project varRealpath = __dirname + "/static" +pathname; Fs.exists (Realpath,function(exists) {if(!exists) { returnpage_404 (req, res, pathname); } Else { //FS's Createreadstream function, which returns the Readstream object varFile =Fs.createreadstream (Realpath); Res.writehead (200, { ' Content-type ': mimetype[realpath.split ('. '). Pop ()] | | ' Text/plain ' }); File.on (' Data ', Res.write.bind (res)); File.on (' Close ', Res.end.bind (res)); File.on (' Error ',function(err) {returnpage_500 (req, res, err); }); } }); }). Listen (1337, ' 127.0.0.1 '); Console.log (' Server running at http://127.0.0.1:1337/');
node. js simplest static file server