利用node构建本地服务

利用node构建本地服务

首先安装下node.js,地址为https://nodejs.org/en/,然后安装npm。

node.js的中文api地址http://nodeapi.ucdok.com/#/api/

一些模块的用法可以在自己的终端试试哦,通过node这个命令进入node.js环境。如下图

利用node构建本地服务,用到的模块有http、fs、path着三个模块,其中http是用来创建服务的;fs时文件模块,可读写等本地文件;path是一套用于处理和转换文件路径的工具集(具体见http://nodeapi.ucdok.com/#/api/path.html)。

这个构建的原理跟nginx代理访问本地页面是一样的~,将ip(port)映射到本地的静态资源的路径,然后根据url的相对路径找到资源,有点表达的词不达意~

说一下简单的流程

  • 利用http模块的createServer方法起一个服务(可以把request和response打印出来哦,加深理解),listen实现对端口的监听
  • 变量staticUrl保存着我们要访问的静态资源的路径。用path解析url得到相对路径,把staticUrl与之拼接起来就可以得到绝对路径了,用强大的fs模块读取文件,就ok了
  • 有可能url访问的不适本地的资源~嘿嘿,我们就要做些处理了,类似如404
  • 由于加载的html带有js img css各种不同类型的文件,用过ajax的就知道我们要设置好请求头了,不过这里我们是将本地的资源返回给浏览器这个客户段,所以我们要设置好响应头~就建立了一个一个公共的mine.js用来存放文件类型

不多说啦,那就直接看下面的代码吧~

var http = require('http');
var fs = require('fs'); 
var path = require('path');
var mine = require('./mine').types;  //content-type格式
//静态资源的路径
var staticUrl = '/Users/admin/Documents/materials/demo/excise';
var server = http.createServer(function(req,res){
    //req,res均为对象,req是http.IncomingMessage的一个实例,res是http.ServerResponse的一个实例
    //console.log(res);
    var url = req.url; 
    //浏览器输入localhost:9000/index.html, 那url == '/index.html'
    //console.log(url);
    var file = staticUrl + url,
        type = path.extname(url);  //path.extname 返回路径中文件的扩展名
    //console.log(type)
    type = type ? type.split('.')[1] : 'unknown'; 
    fs.readFile(file , function(err,data){
        if(err){
            console.log('访问'+staticUrl+req.url+'出错');
            res.writeHeader(404,{
                'content-type' : 'text/html;charset="utf-8"'
            });
            res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
        }else{
            res.writeHeader(200,{
                'content-type' :  mine[type] || 'text/html;charset="utf-8"'
            });
            res.write(data);  //将index.html显示在浏览器(客服端)
        }
        res.end();
    });
}).listen(9000);

console.log('服务器开启成功

访问路径为http://localhost:9000/index.html
');

使用过ajax的筒靴肯定知道contentType,这是对文件类型的设置。由于我们构建的是一个项目的服务,那么文件类型就多了起来,所以建立一个公共的mine.js用来存放文件类型

// 数据格式标签mime的主要类型
// 参考http://www.w3school.com.cn/media/media_mimeref.asp
/*
    application/
    text/
    image/
    audio/
    video/
    chemical/
    message/
    multipart/
    model/
*/

exports.types = {
  "html": "text/html",
  "xml": "text/xml",
  "js": "text/javascript",
  "css": "text/css",
  "json": "application/json",
  "txt": "text/plain",
  "pdf": "application/pdf",
  "doc": "application/msword",
  "xls": "application/vnd.ms-excel",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "bmp": "image/bmp",
  "svg": "image/svg+xml",
  "tiff": "image/tiff",
  "gif": "image/gif",
  "swf": "application/x-shockwave-flash",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "mp3": "audio/mpeg",
  "wmv": "video/x-ms-wmv",
  "avi": "video/x-msvideo",
  "gz": "application/x-gzip",
  "manifest": "text/cache-manifest"
};
原文地址:https://www.cnblogs.com/lyre/p/5620271.html