使用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);

你可能感兴趣的:(Node.js,node.js,http服务器)