ExpressJS基础概念及简单Server架设

时间:2020-12-04 16:39:50

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://*.com/questions/18974436/change-node-modules-location

《七天学会NodeJS》

ExpressJS

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

Express 安装

npm install -g express

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

ExpressJS 架构示意图

ExpressJS基础概念及简单Server架设

参考资料:

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)

加载所需模块

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

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

 app.use(function(req, res, next){
console.log("first middleware");
if (req.url == "/"){
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("Main Page!");
}
next();
}); app.use(function(req, res, next){
console.log("second middleware");
if (req.url == "/about"){
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("About Page!");
}
next();
});

创建服务并监听

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

示例文件 app.js

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

参考资料:

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