码迷,mamicode.com
首页 > Web开发 > 详细

原生node.js创建服务器

时间:2020-02-13 21:04:53      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:center   div   dex   lis   java   content   pat   not found   span   

var http = require(‘http‘);
var fs = require(‘fs‘);
var path = require(‘path‘);


var server = http.createServer((req, res) => {

    console.log("req.url: ", req.url);

    if (req.url === ‘/‘) {
        readFileSend(‘./index.html‘)
    } else {
        readFileSend(req.url)
    }


    function readFileSend(url) {

        let suffix = url.slice( url.lastIndexOf(‘.‘) + 1 );
        writeHead(suffix);

        let fileDir = path.join(__dirname, url)
        console.log(‘fileDir: ‘, fileDir);

        fs.readFile(fileDir, function (err, data) {
            if (err) {
                writeHead(‘html‘, 404);
                res.end("<h1 style=‘text-align: center;‘>404 Not found</h1>");
                console.log(‘Not found File‘);
            } else {
                res.end(data);
            }
        })
    }

    function writeHead(suffix, code = 200) {
        let ContentType = "text/plain"
        switch (suffix) {
            case ‘htm‘: 
            case ‘html‘: ContentType = "text/html"; break;
            case ‘css‘: ContentType = "text/css"; break;
            case ‘js‘: ContentType = "application/javascript"; break;
            case ‘json‘: ContentType = "application/json"; break;
            case ‘mp4‘: ContentType = "video/mp4"; break;
            case ‘jpg‘: 
            case ‘jpeg‘: ContentType = "image/jpeg"; break;
            case ‘png‘: ContentType = "image/png"; break;
            case ‘gif‘: ContentType = "image/gif"; break;
        }
        res.writeHead(code, {
            "Content-Type": ContentType + ";charset=UTF-8"
        });
    }

});



server.listen(4000);

 

原生node.js创建服务器

标签:center   div   dex   lis   java   content   pat   not found   span   

原文地址:https://www.cnblogs.com/zp106/p/12305001.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!