Access static resources

const HTTP = the require ( 'HTTP' ); 
const URL = the require ( 'URL' ); 
const path = the require ( 'path' ); 
const FS = the require ( 'FS' ); 
const MIME = the require ( 'MIME' ); 

App const = http.createServer (); 

the console.log (Global .__ dirname); 
// the console.log (__ filename); 

app.on ( 'request', (REQ, RES) => {
     // Get the user's request path 
    = pathname the let url.parse (req.url) .pathname; 

    pathname = pathname == '/' '/default.html'? : pathname; 

    // converts the user's request to the actual path of the server hard disk path
    realpath = path.join the let (__ dirname, 'public' + pathname); the console.log (realpath);
 // public static resources, such as memory pages placed css file like 
    the let type = mime.getType (realpath) 

    // read file 
    fs.readFile (realpath, (error, Result) => {
         // if the file read failed 
        IF (error =! null ) { 
            res.writeHead ( 404 , {
                 'Content-type': 'text / HTML; charset = UTF8 ' 
            }) 
            res.end ( ' file read failed ' );
             return ; 
        } 

        res.writeHead ( 200 is , {
            'Content-type' : type 
        }) 

        res.end (Result); 
    }); 
}); 

app.listen ( 3000 ); 
the console.log ( 'server startup success')

 

Guess you like

Origin www.cnblogs.com/treasurea/p/11247714.html