06 Node.js study notes the automatic route

In previous documents requested by the client, we have to determine a match in order to return the appropriate data, in fact, we can set up an automatic routing, you can not judge each user to access a file that is

// 1, http and fs loading module 
var http = the require ( 'http' );
 var fs = the require ( 'fs' );
 // 2, create an http service 
var Server = http.createServer ();
 // . 3 set a Http listening port, the browser requests 127.0.0.1:8000 triggered request 
server.listen (8080, function () { 
    console.log ( "start service" ); 
}) 
// 4, listens request request event, setting request, response callback 
server.on ( 'Request', function (REQ, RES) {
     // set a variable with the need to access files stored in the address path 
    var wwwdir = '' ;
     IF (req.url == '/ ' ) { 
        wwwdir= 'index.html' ; 
    } the else {
         // Get setting client requests file path 
        wwwdir + = '/.' req.url; 
    } 
    IF (! wwwdir = null ) {
         // get the file contents 
        fs.readFile (wwwdir, function (error, data) {
             // returns the data to the client 
            res.end (data); 
        }) 
    } 
})

The above code is written is not very strict, a lot of BUG, ​​here only to provide an idea of ​​where.

Guess you like

Origin www.cnblogs.com/juc1024/p/11489419.html