Discuss / JavaScript / 练习

练习

Topic source

失效_

#1 Created at ... [Delete] [Delete and Lock User]
'use strict';

const fs = require('fs'),
    url = require('url'),
    path = require('path'),
    http = require('http');

const root = path.resolve(process.argv[2] || '.');

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

const server = http.createServer( (request, response) => {
    const pathname = url.parse(request.url).pathname;

    let filepath = path.join(root, pathname);

    fs.stat(filepath, (error, stats) => {
        if( !error ){
            if( stats.isFile() ){
                console.log('200' + request.url);
                response.writeHead(200);
            }else{
                filepath = path.join(filepath,'index.html');
                //判断是否存在index.html
                fs.exists(filepath, function(exists){
                    if(exists){
                        console.log('filepath' + filepath);
                        response.writeHead(200);
                    }else{
                        filepath = path.join(root,'default.html');
                        response.writeHead(404); 
                    }
                })  
            }
            fs.createReadStream(filepath).pipe(response);    
        }else{
            console.log('404' + request.url);
            response.writeHead(404);
            response.end('404 Not Found');
        }
    })
})

server.listen(8080);

console.log('Server is running at locallost:8080');

  • 1

Reply