node module built in http

The purpose is to develop Node.js written in JavaScript Web server program. Because JavaScript script actually has dominated the browser side, the advantage is to have the largest number of front-end developers in the world. If you have already mastered the JavaScript front-end development, and then learn how to use JavaScript in the back-end development, it is truly a full stack.

HTTP protocol

To understand how Web server program, first of all, we need to have a basic understanding of the HTTP protocol. If you are not familiar with the HTTP protocol, first look at the HTTP protocol Introduction.

HTTP server

To develop HTTP server program from scratch TCP connection processing, parsing HTTP is unrealistic. These efforts have actually made Node.js comes httpcomplete module. HTTP protocol and the application does not deal directly, but the operation httpprovided by the module requestand responseobjects.

requestObject encapsulates the HTTP request, we call the requestobject's methods and properties can get all the information of the HTTP request;

responseObject encapsulates an HTTP response, we operation responsemethod of an object, you can return the HTTP response to the browser.

Implement an HTTP server program using Node.js is very simple. Let's implement a simple Web application hello.jsthat all requests are returned Hello world!:

'use strict' ; 

// import module http: 
var http = the require ( 'http' ); 

// create http server, and pass the callback function: 
var Server http.createServer = ( function (Request, Response) {
     // Callback receiving a function request and response objects, 
    // get method and an HTTP request URL: 
    the console.log (request.method + ':' + request.url);
     // HTTP response write response 200, and set Content-Type: text / HTML: 
    response.writeHead (200 is, { 'the Type-the content': 'text / HTML' });
     // HTML content of the HTTP response is written response: 
    Response.End ( '<h1 of> the Hello World </! h1 of> ' ); 
});

// let the server listens on port 8080:
server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

At the command prompt, run the program, you can see the following output:

$ node hello.js 
Server is running at http://127.0.0.1:8080/

Do not close the command prompt, direct your browser to http://127.0.0.1 :8080, you can see the contents of the server response: hello world!

Meanwhile, in the command prompt window, you can see the print request information program:

GET: /
GET: /favicon.ico

This is the first HTTP server program we write!

file server

Let us continue to expand at the above Web program. We can set up a directory, and then let the program into a Web file server. To achieve this, we just need to parse request.urlthe path, and then find the corresponding file locally, to send the file contents out on it.

URL parsing need to use Node.js provides urlmodule, it is very simple to use, through parse()a string parsed as a Urltarget:

'use strict';

var url = require('url');

console.log(url.parse('http://user:[email protected]:8080/path/to/file?query=string#hash'));

The results are as follows:

Url {
  protocol: 'http:',
  slashes: true,
  auth: 'user:pass',
  host: 'host.com:8080',
  port: '8080',
  hostname: 'host.com',
  hash: '#hash',
  search: '?query=string',
  query: 'query=string',
  pathname: '/path/to/file',
  path: '/path/to/file?query=string',
  href: 'http://user:[email protected]:8080/path/to/file?query=string#hash' 
}

Deal with local file directory need to use Node.js provides pathmodule, it can be easily constructed catalog:

'use strict' ; 

var path = the require ( 'path' ); 

// parse the current directory: 
var workDir = path.resolve ( '.'); // '/ the Users / Michael' 

// combination full file path: Current directory + 'Pub' + 'index.html': 
var filePath = path.join (workDir, 'Pub', 'index.html' );
 // '/Users/michael/pub/index.html'

Use pathmodule can process file paths associated with the operating system properly. In Windows systems, the path is similar to the return C:\Users\michael\static\index.html, so that we do not care how the path of joining up.

Finally, we implemented a file server file_server.js:

'use strict' ; 

var 
    FS = the require ( 'FS' ), 
    URL = the require ( 'URL' ), 
    path = the require ( 'path' ), 
    HTTP = the require ( 'HTTP' ); 

// command line parameter acquisition root directory, the default is the current directory: 
var the root = path.resolve (process.argv [2] || './static' ); 

the console.log ( 'the Static the dir the root:' + the root); 

// create a server: 
var server http.createServer = ( function (Request, Response) {
     // path URL obtained analogously '/css/bootstrap.css': 
    var pathname = url.parse (request.url).
    pathname;
    // get a local file path corresponding to, similar to '/srv/www/css/bootstrap.css': 
    var filepath = path.join (the root, pathname);
     // Get File Status: 
    fs.stat (filepath, function (ERR , stats) {
         IF (! && ERR stats.isFile ()) {
             // no error and the file exists: 
            the console.log ( '200' + request.url);
             // send a response 200: 
            response.writeHead (200 );
             // the file stream directed Response: 
            fs.createReadStream (filepath) .pipe (Response); 
        } the else {
             // an error or the file does not exist:
            console.log('404 ' + request.url);
            // 发送404响应:
            response.writeHead(404);
            response.end('404 Not Found');
        }
    });
});

server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

There is no need to manually read the file contents. Since the responseobject itself is a Writable Streamdirect use of pipe()the method is realized automatically read the contents of the file, and outputs the HTTP response.

In the command line to run node file_server.js /path/to/dir, put /path/to/dirinto a valid your local directory (to set an absolute path is set, or not set), then enter in your browser http://localhost:8080/index.html:

Html content appeared !!

 

The evolution of the code above, when there is no input url /index.html, or lose only domain names, display the default page index.html

'use strict'
 // build a file server 
var FS = the require ( "FS" ), 
    URL = the require ( "URL" ), 
    path = the require ( "path" ), 
    HTTP = the require ( "HTTP" ); 

// from command-line arguments get root directory, the default is the current directory: 
var root = path.resolve (process.argv [2] || './static'); // set static for static resources directory with the directory 
console.log (process .argv); 
console.log ( 'static root dir:' + root);
 // when using this directory node file_server.js / static run the project 
// root: C: \ run so that static is certainly not without either Or add the path absolute path static folder 

// create the server:
var server=http.createServer(function (Request, Response) {
     // get the URL path, similar to the '/css/bootstrap.css': 
    var pathname = url.parse (request.url) .pathname; // URL address resolution request for 
    console.log ( pathname); //   /index.html 
    // get a local file path corresponding to, similar to '/srv/www/css/bootstrap.css': 
    var filepath = path.join (the root, pathname); 
    the console.log (filepath) ; // C: \ static \ index.html 
    // Get file status: 
    fs.stat (filepath, function (ERR, stats) {
         IF (ERR &&! stats.isFile ()) {
             // no error and the file exists: 
            Console .log ( '200' +request.url);
             // send a response 200: 
            response.writeHead (200 );
             // file stream directed Response: 
            fs.createReadStream (filepath) .pipe (Response); 
        } the else  IF ! (ERR stats.isDirectory && ()) { // if the searched downwardly index.html 
            response.writeHead (404); // reported a 404 
            var testFilePath = path.join (filepath, 'index.html' ); 
            fs.stat (testFilePath, function (ERR, stats ) {
                 IF (! && ERR stats.isFile ()) {  
                    fs.createReadStream (testFilePath) .pipe (Response);
                } 
            }) 
        } the else {
             // an error or the file does not exist: 
            the console.log ( '404' + request.url);
             // send a response 404: 
            response.writeHead (404 ); 
            Response.End ( '404 Not Found' ); 
        } 
    }) 
}); 

// server listens on port 8080 
server.listen (8080 ); 

the console.log ( 'server running IS AT http://127.0.0.1:8080/');

 

Guess you like

Origin www.cnblogs.com/fqh123/p/10994366.html