美文网首页
>>>>> NodeJS搭建本地服务器

>>>>> NodeJS搭建本地服务器

作者: 風隨風去 | 来源:发表于2016-12-07 20:22 被阅读0次
  • 头部模块文件---mine.js
exports.types = {
  "css": "text/css",
  "gif": "image/gif",
  "html": "text/html",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "pdf": "application/pdf",
  "png": "image/png",
  "svg": "image/svg+xml",
  "swf": "application/x-shockwave-flash",
  "tiff": "image/tiff",
  "txt": "text/plain",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "xml": "text/xml"
};

搭建服务器文件---http.js

var PORT = 3000;//端口号

var http = require('http');//协议
var url=require('url');//读取路径模块
var fs=require('fs');//引入文件读取模块
var mine=require('./mine').types;//引入的上面头部文件模块并取到types对象
var path=require('path');//资源路径,符合web服务器路由约定即可

var server = http.createServer(function (request, response) {
    //request用来接收客服端数据,response用来向客服端发送服务器数据
    var pathname = url.parse(request.url).pathname;//解析路径名
    pathname=decodeURI(pathname);//路径解码--可能隐式编码
    var realPath = path.join("文件夹位置", pathname);//实际路径--绝对路径
    var ext = path.extname(realPath);//.html
    ext = ext ? ext.slice(1) : 'unknown';

    //console.log(realPath);
    //exists目标是否存在--true,false
    fs.exists(realPath, function (exists) {
        console.log(exists);//false;
        if (!exists) {
            response.writeHead(404, {//响应写入头部,状态码404--无法找到指定位置的资源
                'Content-Type': 'text/plain'
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {//状态码500--服务器遇到了意料不到的情况,不能完成客户的请求
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {//状态码200--OK  一切正常,对GET和POST请求的应答文档跟在后面
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");//服务器返回给我们的,并写入文件
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

在Node环境下运行http.js开启服务器,在浏览器中输入请求地址,这时为本地,加上端口号和文件即可访问相应文件
*注:文件类型需满足上方mine.js中类型

相关文章

网友评论

      本文标题:>>>>> NodeJS搭建本地服务器

      本文链接:https://www.haomeiwen.com/subject/apkjmttx.html