/ * * * Static server function: Core Module HTTP * initial realization server function * / const HTTP = The require ( 'HTTP' ); // create a server instance object the let server = http.createServer (); // Bind request event server .on ( 'Request', (REQ, RES) => { res.end ( 'Hello' ); }); // listening port access address: localhost: 3000 server.listen (3000 ); // ==== ===================================== http.createServer ((REQ, RES) => { RES .end ( 'OK' ); .}) the listen ( 3000, '196.167.0.8', () => { //At this point can no longer access the localhost, IP address only: 3000 the console.log ( 'running ...' ); });
/ * * * Distribution request processing path * because access localhost: 3000, localhost: 3000 / index.html, localhost: When 3000 / about.html and other pages, display the contents are the same * 1.req object is a Class: http.IncomingMessage examples of objects * 2.res objects are Class: http.ServerResponse instance object * / const HTTP = the require ( 'HTTP' ); http.createServer ((REQ, RES) => { // req.url can obtain the URL path (path after the port) // res.end (req.url); IF (req.url.startsWith ( '/ index' )) { // the client respective content write, write back for multiple spelling together res.write ( 'Hello' ); res.write ( 'available for purchase' ); // End to complete response, with no parameters can only be performed once res.end ( 'index' ); } the else IF (req.url.startsWith ( '/ About' )) { res.end ( 'About' ); } the else { res.end ( 'NO Content' ); } } ) .listen ( 3000, '196.167.0.8', () => { // At this point can no longer access the localhost, IP address only: 3000 the console.log ( 'running ...' ); });
/ * * * Full page response information, create multiple files, using the route distribution functions are carried out in response to different pages * / const HTTP = The require ( 'HTTP' ); const path = The require ( 'path' ); const FS the require = ( 'FS' ); // read the contents of the file based on the path, and accordingly to the browser // extracted as a separate method the let readFile = (URL, RES) => { fs.readFile (path.join (__dirname, URL), 'UTF8', (ERR, fileContent) => { IF (ERR) { res.end ( 'Server error' ); } the else { res.end (fileContent); } }); } //Distribution processing path http.createServer ((REQ, RES) => { IF (req.url.startsWith ( '/ index' )) { readFile ( 'index.html' , RES); } the else IF (req.url.startsWith ( '/ About' )) { readFile ( 'about.html' , RES); } the else IF (req.url.startsWith ( '/ List' )) { readFile ( 'the list.html' , RES); } the else { // set the appropriate type and code, or does not respond normally administered not Skip res.writeHead (200 is, { 'the type-the Content': 'text / Plain; charset = UTF8' }); res.end ('404 Not found' ); } }) the listen (. 3000, '196.167.0.8', () => { // At this point can no longer access the localhost, IP address only: 3000 the console.log ( 'running ... ' ); });
With more and more branches of the page, above is not flexible enough, you should go get this file from url (use req.url get back to that port number path)
/ * * * Path improved distribution * / const HTTP = the require ( 'HTTP' ); const path = the require ( 'path' ); const FS = the require ( 'FS' ); // introduced mime module, is based on the role url suffix, corresponding to the return Content-type, or a file type you pass Content-type, which returns the corresponding suffix // mounting mime modules: the install NPM mime --save const = mime the require ( 'mime' ); // process route distribution http.createServer ((REQ, RES) => { fs.readFile (path.join (__ dirname, req.url), (ERR, fileContent) => { IF (ERR) { // does not find the corresponding files // header information setting response to avoid distortion res.writeHead (404 , { 'the Type-the Content': 'text / Plain; charset = UTF8' }); // res.writeHead (404, { 'the Type-the Content': 'text / Plain; charset = UTF8'} ); res.end ( 'missing page' ); } the else { // Get the suffix of the requested file // default type: // the let DTYPE = 'text / HTML'; // the let EXT = path.extname (REQ. URL); // the console.log (EXT); // the console.log (MIME [EXT]); // the console.log (mime.getType (path.join (__ dirname, req.url))); // If the requested file suffix yo reasonable response on the acquired standard format // if there exists mime suffix, the suffix type override the default //This approach does not work, has been in the default type, the cycle can not enter / * IF (MIME [EXT]) { DTYPE = MIME [EXT]; } * / // mime.getType (filePath) the let DTYPE = mime.getType ( path.join (__ dirname, req.url)); // if the type is text, it is necessary to set its encoding type IF (dType.startsWith ( 'text' )) { DTYPE + = '; charset = UTF8' } // set response headers res.writeHead (200 is, { 'the Type-the Content' : DTYPE}); res.end (fileContent); } }); }) the listen (. 3000, () => { the console.log ( 'running. .. '); });
For static server resources to optimize this function, you can extract this part functions as a separate module for later use.
/ * * * Extraction module: 01.js file * / const HTTP = the require ( 'HTTP' ); const path = the require ( 'path' ); const FS = the require ( 'FS' ); const MIME = the require ( 'MIME ' ); // the root represents the root path of the file exports.staticServer = (REQ, RES, the root) => { fs.readFile (path.join (the root, req.url), (ERR, fileContent) => { IF ( ERR) { // does not find the corresponding files // setting response header information and avoid distortion res.writeHead (404 , { 'the Type-the Content': 'text / Plain; charset = UTF8' }); // res.writeHead (404, { 'the Type-the Content': 'text / Plain; charset = UTF8'}); res.end ( 'missing page' ); } the else {the let DTYPE = mime.getType (path. the Join (__ dirname, req.url)); // if the type is text, it is necessary to set its encoding type IF (dType.startsWith ( 'text' )) { DTYPE + = '; charset = UTF8' } // set the response header information res.writeHead (200 is, { 'the Type-the Content' : DTYPE}); res.end (fileContent); } }); }
/** * 测试模块:02.js文件 */ const http = require('http'); const path = require('path'); const ss = require('./03.js'); http.createServer((req,res) => { ss.staticServer(req,res,path.join(__dirname)); }).listen(3000,() => { console.log('running...'); });