您好,欢迎来到爱玩科技网。
搜索
您的当前位置:首页使用Node.js创建一个简单的本地页面服务器

使用Node.js创建一个简单的本地页面服务器

来源:爱玩科技网

使用Node.js可以很简单的创建一个HTTP服务器,但是如果想要调试本地代码,就需要通过Node来查找本地资源文件并返回。
所以参考代码如下,注意我这里只支持html,js和css并未处理。

const http = require('http');
const fs = require('fs');
const rootPath = 'H:/';


http.createServer(function(request, response){
        let filePath =  rootPath + request.url;
        fs.readFile(filePath,'binary',function(err,file){
            if(err){
                response.writeHead(500, { "Content-Type": "text/plain" });
                response.write(err + "\n");
                response.end();
                return;
            }else{
                if(/\.js/.test(filePath)){
                    response.writeHead(200, { "Content-Type": "text/javascript" });
                }else if(/\.css/.test(filePath)){
                    response.writeHead(200, { "Content-Type": "text/css" });
                }else if(/\.html/.test(filePath)){
                    response.writeHead(200, { "Content-Type": "text/html" });
                }else if(/\.webm/.test(filePath)){
                    response.writeHead(200, { "Content-Type": "application/octet-stream" });
                }else{
                    response.writeHead(200, { "Content-Type": "text/plain" });
                }
                response.write(file,'binary');
                response.end();
            }
        })
}).listen(8088);

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- aiwanbo.com 版权所有 赣ICP备2024042808号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务