zoukankan      html  css  js  c++  java
  • 原生node.js创建服务器

    // 需要服务器环境进行代码调试时直接运行这段代码, 然后打开http://localhost/即可, 方便的很.
    
    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(80);
     
  • 相关阅读:
    洛谷P3811题解
    洛谷P3353在你窗外闪耀的星星-题解
    Map根据value来排序
    java8 groupby count
    Java反射
    maven profile环境切换
    获取nginx代理情况下的真实ip
    获取request里header的name和value
    git 删除iml文件
    java list 排序
  • 原文地址:https://www.cnblogs.com/zp106/p/12305001.html
Copyright © 2011-2022 走看看