黑猴子1357751126@qq.com

喜欢敲代码,喜欢设计,旅游。我们一起吧!!!

http服务器(nodejs)

Nodejs的http服务器的构建

var PORT = 8888;

var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./custom').types;
var path=require('path');

var server = http.createServer(function (request, response) {
    console.log( url.parse(request.url) );
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("project", pathname);
    console.log(realPath);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';
    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(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, {
                        'Content-Type': 'text/plain'
                    });
                    response.end(err);
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {
                        'Content-Type': contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

custom.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服务器 nodejs
个人分类: nodejs
上一篇手机晃动监测
下一篇js
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭