node 搭建 server,不使用express、ejs

有个静态页面需要展示,参考下面的这个人的做法

来自: node部署静态页面上线.

测试环境:ubuntu 16
node Version : v10.15.0

注意使用 ${} 模板的时候需要使用反引号,而不是单引号和双引号

不需要访问目录,修改代码如下

var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
var cp = require('child_process');

var httpServer = http.createServer(processRequest);

var port = 7666;
httpServer.listen(port, function () {
    console.log(`app is running at port:${port}`);
    console.log(`url is : http://localhost:${port}`);
    cp.exec(`explorer http://localhost:${port}`, function(){});
});

function processRequest(request, response){
    var mime = {
        "css": "text/css",
        "gif": "image/gif",
        "html": "text/html",
        "ico": "image/x-icon",
        "jpeg": "image/jpeg",
        "jpg": "image/jpeg",
        "js": "text/javascript",
        "json": "application/json",
        "pdf": "application/pdf",
        "png": "image/png",
        "svg": "image/svg+xml",
        "swf": "application/x-shockwave-flash",
        "tiff": "image/tiff",
        "txt": "text/plain",
        "wav": "audio/x-wav",
        "wma": "audio/x-ms-wma",
        "wmv": "video/x-ms-wmv",
        "xml": "text/xml"
    };
    var requestUrl = request.url;
    var pathName = url.parse(requestUrl).pathname;

    var pathName = decodeURI(pathName);

    if(!pathName.endsWith('/')&&path.extname(pathName) ===''){
        pathName += '/';
        var redirect = "http://"+request.headers.host+pathName;
        response.writeHead(301, {
            location: redirect
        });
        response.end();
    }

    var filePath = path.resolve(__dirname+pathName);
    console.log("request path is: "+filePath);
    var ext = path.extname(pathName);
    ext = ext ? ext.slice(1) : 'unknown';

    var contentType = mime[ext] || "text/plain";

    fs.stat(filePath, (err, stats) => {
        if(err) {
            response.writeHead(404, {"content-type":"text/html"});
            response.end("<h1> 404 not found </h1>");
        }
        if(!err && stats.isFile()){
            readFile(filePath, contentType);
        }
        function readFile(filePath, contentType){
            response.writeHead(200, {"content-type": contentType});
            var stream = fs.createReadStream(filePath);
            stream.on('error',function(){
                response.writeHead(500, {"content-type": contentType});
                response.end("<h1>500 </h1>");
            });
            stream.pipe(response);
        }
    });
}

猜你喜欢

转载自blog.csdn.net/xsjyahoo/article/details/87719148