. 1 const = the require HTTP ( 'HTTP' ); 2 const the require FS = ( 'FS' ); . 3 const = path the require ( 'path' ); . 4 const = the require URL ( 'URL' ); . 5 . 6 // . 1. create a server . 7 http.createServer ((REQ, RES) => { . 8 // 1.1 to acquired path url . 9 the let pathUrl = url.parse (req.url); 10 the let pathName = pathUrl.pathname; . 11 // the console.log (pathName); 12 is 13 is // 1.2 suffix extraction 14 IF {(pathName.lastIndexOf () === -1 '.')// No 15 pathName + = '/index.html' ; 16 } . 17 18 is // 1.3 suffix processing . 19 the let fileURL = path.join (__ dirname, pathName); 20 is // the console.log (fileURL); 21 is 22 is / / take suffix 23 is the let extname = path.extname (fileURL); 24 25 // 1.4 read the file 26 is fs.readFile (fileURL, (ERR, Data) => { 27 IF (ERR) { // no pages found 28 RES .writeHead (404, { 'content- type': 'text / html; charset = utf-8'}); 29 res.end ( '<h1 of> 404, the current page does not exist </ h1 of>!' ); 30 } the else { // find the resource 31 is the getContentType (extname, (contentType) => { 32 // Console .log (contentType); 33 is res.writeHead (200 is, { 'Content-type' :} contentType); 34 is res.end (Data); 35 }); 36 } 37 [ }); 38 is .}) the listen (3000 ) ; 39 40 41 is the let the getContentType = (extname, the callback) => { 42 is // 读取文件 43 fs.readFile(path.join(__dirname, 'mime.json'), (err, data)=>{ 44 if(err){ 45 throw err; 46 } 47 let mineJson = JSON.parse(data); 48 let contentType = mineJson[extName] || 'text/plain'; 49 callback && callback(contentType); 50 }) 51 };
http://localhost:3000/static/index.html