首页 > Web开发 > 详细

ExpressJS基础概念及简单Server架设

时间:2015-10-20 22:50:21      阅读:419      评论:0      收藏:0      [点我收藏+]

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

ExpressJS基础概念及简单Server架设

原文:http://www.cnblogs.com/isun/p/4889648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!