zoukankan      html  css  js  c++  java
  • 用nodejs搭建一个简单的服务监听程序

    作为一个从业三年左右的,并且从事过半年左右PHP开发工作的前端,对于后台,尤其是对以js语言进行开发的nodejs,那是比较有兴趣的,虽然本身并没有接触过相关的工作,只是自己私下做的一下小实验,但是还是记录一下方便以后复习!

    今天主要记录一下,很久以前用nodejs制作一个简单的服务监听程序的一些过程!

    大家都知道,通过nodejs可以对前台请求进行监听,这里就放一个官网的hello world例子吧:

    var http = require('http');
    
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World
    ');
    }).listen(1337, '127.0.0.1');
    
    console.log('Server running at http://127.0.0.1:1337/');
    

    以上代码相信了解过node的童鞋应该都会比较熟悉!

    那么node既然可以监听请求,那么是不是就可以根据前台的不同请求返回不同的文件或内容?这不就是一个简单的服务器了么!抱着这样的想法,简单实验了一下,我们都知道,服务器可以根据请求的文件不同,会使用相应mine类型的!比如../index.css使用的mine类型就是text/css!那么,我们是不是应该有个常用mine类型的一个简单配置?这里,做了个简单的mine配置文件mine.js,用json来存放一下常用的格式:

    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"
    };
    

    当然,除了这些以外还有很多其他格式,这里就不一一举例了!

    好了,有了mine格式对应的文件配置文件,接下来就简单了,首先得根据官网例子搭建一个监听程序,然后在监听程序中添加一下简单的www.baidu.com/这个样的链接默认打开文件的处理,以及相对链接的补全等!当然还得做一下简单的错误处理,如404,500等!具体看代码:

    /*
     *搭建http服务器,监听http请求
     */
    var http = require("http"),
    fs = require('fs'),
    path = require('path'),
    mine = require('./mine').types;
    url = require('url');
    //定义简单的工具
    //获取当前时间
    var date = function(ms) {
        var date = ms ? new Date(ms) : new Date(),
        mon = date.getMonth() >= 10 + 1 ? '-' : '-0',
        d = date.getDate() >= 10 ? '-' : '-0',
        hour = date.getHours() >= 10 ? ' ' : ' 0',
        min = date.getMinutes() >= 10 ? ':' : ':0',
        sec = date.getSeconds() >= 10 ? ':' : ':0';
        return date.getFullYear() + mon + (date.getMonth() + 1) + d + date.getDate() + hour + date.getHours() + min + date.getMinutes() + sec + date.getSeconds();
    },
    //定义输出log日志方法,带上时间,方便调试
    DebugLog = function(mes) {
        var now = date();
        console.log(now + " " + mes);
    };
    //服务监听
    exports.server = function() {
        http.createServer(function(req, res) {
        	var pathname = url.parse(req.url).pathname,//获取url中的文件名
        	pathname = (pathname !== "/" && pathname) ? pathname : "/index.html";//处理链接以'/'结尾的情况
            var realPath = path.join("../", path.normalize(pathname.replace(/../g, ""))),//将链接转换成物理路径
            ext = path.extname(realPath);
            ext = ext ? ext.slice(1) : 'unknown';//获取文件扩展名
            //查找文件
            fs.exists(realPath, function (exists) {
                if (!exists) {//处理404
                    res.writeHead(404, {
                        'Content-Type': 'text/plain'
                    });
    
                    res.write("This request URL " + pathname + " was not found on this server.");
                    res.end();
                } else {//读取文件
                    fs.readFile(realPath, "binary", function (err, file) {
                        if (err) {//程序出错报500错误
                            res.writeHead(500, {
                                'Content-Type': 'text/plain'
                            });
                            res.end(err);
                        } else {//正常返回文件
                            var contentType = mine[ext] || "text/plain";//根据mine.js中的配置设置对应的contentType
                            res.writeHead(200, {
                                'Content-Type': contentType
                            });
                            res.write(file, "binary");
                            res.end();
                        }
                    });      
                }
            });
        }).listen(8888, 'localhost');
        tool.DebugLog("http服务启动,开始监听127.0.0.1:8888的http请求!");
    }
    

    ok,代码到这里基本就结束了,当然这只是最简单的功能,大家可以自己去丰富!本文就到这里吧,欢迎大家交流讨论!

  • 相关阅读:
    魔方
    js烟花特效
    面试cookie
    扩展日期插件
    通过javascript实现1~100内能同时被2和3整除的数并生成如下表格
    用三或四个个div标签实现工字效果
    2015_WEB页面前端工程师_远程测题_东方蜘蛛_1
    js公有、私有、静态属性和方法的区别
    Docker libnetwork(CNM)设计简介
    kubernetes,Docker网络相关资料链接
  • 原文地址:https://www.cnblogs.com/xjser/p/4971159.html
Copyright © 2011-2022 走看看