原生node.js创建服务器

Posted 虚拟的现实

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原生node.js创建服务器相关的知识,希望对你有一定的参考价值。

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创建服务器的主要内容,如果未能解决你的问题,请参考以下文章

node.js (原生模板引擎模板)

Node.js JavaScript 片段中的跳过代码

使用Node.js原生API写一个web服务器

nodejs搭建服务器手册

nodejs搭建服务器手册

nodejs搭建服务器手册