zoukankan      html  css  js  c++  java
  • nodejs server启动写法

    http://www.phpstudy.net/c.php/18720.html

    node不利用框架怎么实现对静态HTML、css、js的服务?
    初学nodeJS,在使用nodejs构建静态文件服务器的时候,遇到下面问题。
    用户请求index.html时,我使用fs.readFile读取index.html并将data返回,代码如下:
    
    function serverStatic(req,res){
        var filePath;
        if(req.url==="/"){
            filePath =  "index.html";
        } else{
            filePath = "./" + url.parse(req.url).pathname;
        }
               
             fs.exists(filePath,function(err){
                 if(err){
                      send404(res);
                 }else{
                     fs.readFile(filePath,function(err,data){
                         if(err){
                             res.end("<h1>500</h1>服务器内部错误!");
                         }else{
                         res.writeHead(200,{'content-type':'text/html'});
                             res.end(data.toString());
                         }
                     });//fs.readfile
                 }
             })//path.exists
                  
    }//serverStatic
    那么问题来了,如果我的HTML页面引用了外部的css或者js,那么这些外部文件不会被加载···
    这个问题怎么解决?
    
    尝试:
    index源码:
    
    <!doctype html>
    <html>
    <head>
    <meta charset='utf-8'>
    <link href="css/index.css">
        </head>
        <body>
            <a href="flexbox.html">看看伸缩盒?</a>
        </body>
        </html>
    css:
    
    body{background-color:red;}
     
    app.js:
    
    var http=require('http');
    var fs=require('fs');
    var url=require('url');
    var path=require('path');
    var PORT=9090;
    //添加MIME类型
    var MIME_TYPE = {
        "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"
    };
    
    var server = http.createServer(serverStatic);
    function serverStatic(req,res){
        var filePath;
        if(req.url==="/"){
            filePath =  "index.html";
        } else{
            filePath = "./" + url.parse(req.url).pathname;
        }
    
        fs.exists(filePath,function(err){
            if(!err){
                send404(res);
            }else{
                var ext = path.extname(filePath);
                ext = ext?ext.slice(1) : 'unknown';
                var contentType = MIME_TYPE[ext] || "text/plain";
                fs.readFile(filePath,function(err,data){
                    if(err){
                        res.end("<h1>500</h1>服务器内部错误!");
                    }else{
                        res.writeHead(200,{'content-type':contentType});
                        res.end(data.toString());
                    }
                });//fs.readfile
            }
        })//path.exists
    
    }
    
    server.listen(PORT);
    console.log("Server runing at port: " + PORT + ".");
    
    function send404(res){
        res.end("<h1>404</h1><p>file not found</p>")
    }
    chrome查看网络:
    
    我的文件结构
    
    
    那么问题来了,你的为请求的每个资源写读取文件处理
    
    前几天刚有人问这个问题的
    http://.com/q/1010000004317668?_ea=567469
    利用nodejs搭建静态文件服务器
    
    下面是一个静态文件访问的模块
    
    /**
     * 引入模块
     * @type {[type]}
     */
    var fs   =require("fs");
    var mime =require("mime");
    var path =require("path");
    
    /*******************************************************************************************/
    
    /**
     * [Send 创建发送响应对象]
     */
    function Send(){};
    Send.prototype.cache={};//设置缓存变量,因为缓存变量比读取文件要快
    
    /**
     * 错误404页面
     * @param  {[type]} res [description]
     * @return {[type]}     [description]
     */
    Send.prototype.err404 = function(res){
        res.writeHead(404,{"Content-Type":"text/plain"});
        res.write("404 Not Fount !");
        res.end();
    };
    
    
    
    /**
     * 正确访问页面
     * @param  {[type]} res         [description]
     * @param  {[type]} fileName    [description]
     * @param  {[type]} fileContent [description]
     * @return {[type]}             [description]
     */
    Send.prototype.sendFile = function(res,fileName,fileContent){
        res.writeHead(200,{"Content-Type":mime.lookup(path.basename(fileName))});
        res.end(fileContent);
    
    };
    
    
    
    /**
     * 发送静态页面方法
     * @param  {[type]} res     [description]
     * @param  {[type]} absPath [description]
     * @return {[type]}         [description]
     */
    Send.prototype.serveStatic = function(res,absPath){
        var _this=this;
        if(this.cache[absPath]){
            this.sendFile(res,absPath,this.cache[absPath]);
        }else{
            fs.exists(absPath,function(exists){
                if(exists){
                    fs.readFile(absPath,function(err,data){
                        if(err){
                            _this.err404(res);
                        }else{
                            _this.sendFile(res,absPath,data);
                        }
                    })
                }else{
                    _this.err404(res);
                }
            })
    
        }
    };
    
    
    
    Send.prototype.staticDirectory=function(req,url){
        var filePath=false;
        if(new RegExp("^/"+url+"/.*").test(req.url)){
             filePath=url+req.url;
        }
        var absPath="./"+filePath;
    
        return absPath;
    
    }
    
    
    
    
    
    
    /*******************************************************************************************/
    
    
    module.exports=Send;
    
    
    
    调用方法
    
    /**
     * 引入HTTP组建,创建HTTP服务器的核心组件
     * @type {[type]}
     */
    var http=require("http");
    var sio=require("socket.io");
    
    /**
     * 引入自定义组件,
     * @type {[type]}
     */
    var staticService=require("./modules/staticService");
    
    
    
    /*************************************************/
    
    
    /**
     * 创建http服务
     * @param  {[type]} req    [description]
     * @param  {[type]} res){                 var filePath [description]
     * @return {[type]}        [description]
     */
    var server = http.createServer(function(req,res){
        var send=new staticService();
        var absPath=send.staticDirectory(req,"public")
        send.serveStatic(res,absPath);
    });
    
    server.listen(8200,function(){
        console.log("Http server create success on : localhost:8200");
    })
    
    
    
    fs.exists(filePath,function(err)
    如果文件存在,回掉函数的第1个参数为true
    
    var http=require('http');
    var fs=require('fs');
    var url=require('url');
    var path=require('path');
    var PORT=9090;
    //添加MIME类型
    var MIME_TYPE = {
        "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"
    };
    
    var server = http.createServer(serverStatic);
    function serverStatic(req,res){
        var filePath;
        if(req.url==="/"){
            filePath =  "CSSTest.html";
        } else{
            filePath = "./" + url.parse(req.url).pathname;
        }
    
        fs.exists(filePath,function(err){
            if(!err){
                send404(res);
            }else{
                var ext = path.extname(filePath);
                ext = ext?ext.slice(1) : 'unknown';
                var contentType = MIME_TYPE[ext] || "text/plain";
                fs.readFile(filePath,function(err,data){
                    if(err){
                        res.end("<h1>500</h1>服务器内部错误!");
                    }else{
                        res.writeHead(200,{'content-type':contentType});
                        res.end(data.toString());
                    }
                });//fs.readfile
            }
        })//path.exists
    
    }
    
    server.listen(PORT);
    console.log("Server runing at port: " + PORT + ".");
    问题已解决,link css的时候,不能忘了 rel="stylesheet"
  • 相关阅读:
    使用POI读取excel文件内容
    有序链表
    jQuery Validate验证框架详解
    怎样在VS2010中打开VS2012的项目
    在Win8.1系统下如何安装运行SQL Server 2005
    SQL2005 2008配置错误,无法识别的配置节 system.serviceModel machine.config配置文件有问题
    深入浅出学Spring Data JPA
    Java 学习摘要
    JFinal
    spring 4 + jpa(hibernate 3/4) + spring mvc 多数据源配置
  • 原文地址:https://www.cnblogs.com/jcz1206/p/6409787.html
Copyright © 2011-2022 走看看