zoukankan      html  css  js  c++  java
  • Node.js搭建本地服务,读取css/js/img/html等各种格式文件

    项目文件路径:

    http.js

    这里用到两个JS文件,http.js和mime.js
    http.js :创建一个httpServer并监听3000端口

    var PORT = 3000;
    
    var http = require('http');
    var url = require('url');
    var fs = require('fs'); //fs模块是用于读取文件
    var mime = require('./mime').types;
    var path = require('path');
    
    var server = http.createServer(function(request, response) {
    var pathname = url.parse(request.url).pathname;
    var realPath = path.join("frontEnd", pathname);//webapp就是放置一些静态资源文件的目录,这个可以根据自己的项目需求作修改
    //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 = mime[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 + ".");
    

    使用mime模块设定文件类型

    什么是mime?
    MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型。是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。
    上面http.js中引入了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",
    "woff": "application/x-woff",
    "woff2": "application/x-woff2",
    "tff": "application/x-font-truetype",
    "otf": "application/x-font-opentype",
    "eot": "application/vnd.ms-fontobject"
    };
    

    然后打开命令行,输入命令:

    node http 运行成功如图所示

    然后浏览器输入http://127.0.0.1:3000/index.html 就可以访问拉

  • 相关阅读:
    使Eclipse下支持编写HTML/JS/CSS/JSP页面的自动提示
    SpringMVC与Struts2的对比
    事务不提交,也有可能写redo和数据文件
    14.4.1 InnoDB Startup Configuration
    SLB 权重问题
    perl 访问网站一些useragent的设置
    14.3.5.3 How to Minimize and Handle Deadlocks 如何减少和处理死锁
    nginx 区分pc和mobile 到不同的404页面
    dokcer 运行和进入容器
    docker 私有仓库查询
  • 原文地址:https://www.cnblogs.com/midnight-visitor/p/14069321.html
Copyright © 2011-2022 走看看