码迷,mamicode.com
首页 > Web开发 > 详细

创建web服务器

时间:2017-11-30 16:17:25      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:资源   style   创建   serve   pes   export   flash   this   pdf   

用node创建本地web服务

1,创建本地文件server.js

var http = require(‘http‘);
var url=require(‘url‘);
var fs=require(‘fs‘);
var mine=require(‘./mime‘).types;
var path=require(‘path‘);

//创建服务器  
http.createServer(function(request, response) {  
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("assets", pathname);
    
    var ext = path.extname(realPath);
    if (ext == "") {
        ext = ".html";
        realPath += "index.html"; 
    }
    
    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();
                }
            });
        }
    });
}).listen(8080); 

2,创建加载类型mime.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",
  "mp3": "audio/mpeg",
  "ogg": "audio/ogg",
  "zip": "application/zip"
};

3,创建一个文件夹assets放资源

4 node server.js运行

创建web服务器

标签:资源   style   创建   serve   pes   export   flash   this   pdf   

原文地址:http://www.cnblogs.com/maxwell-xu/p/7929461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!