zoukankan      html  css  js  c++  java
  • ExpressJS基础概念及简单Server架设

    NodeJS

    Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动非阻塞式 I/O 的模型,使其轻量又高效。Node.js 的包管理器 npm,是全球最大的开源库生态系统。

    NodeJS安装:http://nodejs.cn/

    模块(module)路径解析规则:

    1 内置模块    如果 require 函数请求的是一内置模块,如 http、fs等,则直接返回内部模块的导出对象。

    2 node_modules 目录    NodeJS定义了一个特殊的node_modules 目录用于存放模块。例如某个模块的绝对路径是 /home/user/hello.js,在该模块中使用 require('foo/bar') 方式加载模块时,则NodeJS依次尝试使用下面的路径。

      /home/user/node_modules/foo/bar

      /home/node_modules/foo/bar

      /node_modules/foo/bar

    3 NODE_PATH 环境变量    NodeJS可通过 NODE_PATH 环境变量来指定额外的模块搜索路径。例如定义了以下 NODE_PATH 变量值:

      NODE_PATH=/home/user/lib;/home/lib

      当使用 require('foo/bar') 的方式加载模块时,则 NodeJS 依次尝试以下路径。

      /home/user/lib/foo/bar

      /home/lib/foo/bar

    参考资料

    Change node_modules location http://stackoverflow.com/questions/18974436/change-node-modules-location

    《七天学会NodeJS》

    ExpressJS

    Express 是一个基于 Node.js 平台的极简、灵活的 web 应用开发框架,它提供一系列强大的特性,帮助你创建各种 Web 和移动设备应用。

    Express 安装

     1 npm install -g express 

    -g 表示全局安装 ExpressJS,可以在任何地方使用它。

    ExpressJS 架构示意图

    参考资料:

    Creating RESTful APIs With NodeJS and MongoDB Tutorial http://adrianmejia.com/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/#expressjs

    ExpressJS中文网 http://www.expressjs.com.cn/

    创建服务(Server)

    加载所需模块

     1 var express = require("express"); 2 var http = require("http"); 

    添加中间件(Middleware)作 request 拦截和处理分发

     1 app.use(function(req, res, next){
     2     console.log("first middleware");
     3     if (req.url == "/"){
     4         res.writeHead(200, {"Content-Type": "text/plain"});
     5         res.end("Main Page!");
     6     }
     7     next();
     8 });
     9 
    10 app.use(function(req, res, next){
    11     console.log("second middleware");
    12     if (req.url == "/about"){
    13         res.writeHead(200, {"Content-Type": "text/plain"});
    14         res.end("About Page!");
    15     }
    16     next();
    17 });

    创建服务并监听

     1 http.createServer(app).listen(2015); 

    示例文件 app.js

    运行 NodeJS,并访问 http://localhost:2015/

    参考资料:

    透析Express.js http://www.cnblogs.com/hyddd/p/4237099.html

  • 相关阅读:
    【NOIP模拟】寻找
    【NOIP模拟】行走
    【UVA11795】 Mega Man's Mission
    【UVA11825】Hackers' Crackdown
    【UVA1252】Twenty Questions
    BZOJ1718: [Usaco2006 Jan] Redundant Paths 分离的路径
    BZOJ1151: [CTSC2007]动物园zoo
    BZOJ1123: [POI2008]BLO
    BZOJ1040: [ZJOI2008]骑士
    POJ3417:Network
  • 原文地址:https://www.cnblogs.com/isun/p/4889648.html
Copyright © 2011-2022 走看看