Node getting-started
-
Upload
lylijincheng -
Category
Technology
-
view
1.572 -
download
7
description
Transcript of Node getting-started
Node: Getting Started
主要内容
• 基础概念
• 创建Node应用的基础设施
• Node 应用简单示例
• Express Web 框架
什么是Node?
Node 是建立在Chrome浏览器所使用的JavaScript运行环
境上,用来创建快速,可扩展的Web应用程序的平台。
Node的几个特点
• event-driven
• non-blocking I/O model
• single-threaded
• lightweight and efficient
最简单的服务器
app.js: var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
在终端运行: node app.js
> Server running at http://127.0.0.1:1337/
REPL
REPL(发音 “repple”): Read-Eval-Print-Loop,
a Nodejs shell.
创建Node应用的基础设施
• 核心模块
• 路由控制
• 数据持久化
• 中间件
• 其他模块
核心模块
• EventEmitter 模块
• HTTP(S) 模块
• File System 文件系统模块
• Utilities 实用对象模块: util.inherits(constructor, super),
util.isArray(object), ...
• Socket, Stream 模块
• 全局(global) 对象: process, Buffer, …
路由控制
路由处理来自一个URL的数据请求。
路由方法的主要作用是在URI中提取我们需要的信息,通
常使用一些模式匹配,使用这些信息来处理相应的动作,
并把信息传递给处理程序。
创建 RESTful Web API
REST (Representational State Transfer) 意味着支持 HTTP PUT 和 DELETE 方法,同时还有 GET 和 POST方法的能力。
Express 路由使用 app.VERB() 方法来管理。VERB指HTTP方法之一,例如 app.get(), app.put().
Http Verb Route Intro
GET /user/:id 用Id读取用户信息
POST /create 创建一个新用户
PUT /update/:id 修改用户信息
DELETE /delete/:id 删除一个用户
数据持久化
MongoDB,document-oriented storage.
MongoDB是面向文档的数据存储,是一种NoSQL数据库。
其结构类似于:db -> collection -> document
Redis,advanced key/value store.
Redis 提供了高性能的键/值对存储。
MongoDB
MongoDB使用BSON格式来存储数据。在Node中使用MongoDB有两种基本方式,引入两个不同的模块
1. MongoDB Native Node.js Driver, 原生MongDB为Node开发的驱动模块。
2. Mongoose, 提供ORM(Object Relational Mapping)支持的对象建模工具。
相比而言,Mongoose提供了更加抽象的接口,使用 Schema 对象定义数据模型。
定义数据模型和实例
定义数据模型:
var HobbySchema = new Schema({
name: { type: String, required: true, trim:
true }
});
var UserSchema = new Schema({
id: { type: Number, required: true, trim: true,
unique: true },
name: { type: String, required: true, trim:
true },
birthday: Date,
hobbies: [HobbySchema]
});
var UserModel = model(‘UserModel’, UserSchema);
创建对象实例:
var lily = new UserModel({
id: lily,
name: Lily Allen,
birthday: new Date(2012, 11, 20),
hobbies: ['reading', 'music']
});
数据库连接与操作
连接到mongoose数据库
mongoose.connect(‘mongodb://127.0.0.1/mydb’);
或
mongoose.connect(‘'mongodb://username:passwor
d@host:port/database?’);
mongoose.connection.on(‘open’, function() {
console.log(‘Connected to Mongoose’);
});
数据库操作:
lily.save(function(err, data) { });
UserModel.find({id: 'lily'},
function(err, doc) { });
UserModel.update({id: 'lily'},
function(err, doc) { });
UserModel.remove({id: 'lily'},
function(err, doc) { });
Redis
Redis 是一种键/值对数据存储(key/value store).
通常,Redis将数据存储于内存中,或被配置为使用虚拟内存。通过两种方式可
以实现数据持久化:使用快照的方式,将内存中的数据不断写入磁盘;或使用类
似MySQL的日志方式,记录每次更新的日志。前者性能较高,但是可能会引起一
定程度的数据丢失;后者相反。
创建一个Redis客户端:
var client = redis.createClient();
或者,带有三个可选的参数:
var client = redis.createClient(host, port, options);
中间件
中间件(Middleware, http://en.wikipedia.org/wiki/Middleware)
一般来讲,作为开发者,中间件是存在于你和底层系统之间的软件,系统可以指操作系统或一些底层的技术。更具体地说,中间件是应用程序和底层系统之间的通信链。
Connect (http://www.senchalabs.org/connect/)是为Node提供的一个可扩展的HTTP服务框架,提供高性能的中间件。Connect中有10多个中间件,可以在应用中使用其中的一个或多个。
例如,favicon, logger, static, bodyParser, methodOverride...
其他模块
socket.io (http://socket.io/)
Jade - template engine (http://jade-lang.com/)
underscore (https://npmjs.org/package/underscore)
辅助模块:url, path, querystring, ...
示例:创建一个文件服务器
所需模块: • http, 创建服务器并监听请求
• path, 处理文件和路径
• fs, 提供文件系统读写等常用操作
http.createServer(function(req, res) {
// 当一个请求发生时,解析请求的URL确定文件的位置
// 检查并确认此文件的存在性
// 如果文件不存在作出相应的响应
// 如果文件存在,打开后读取数据
// 准备一个响应头
// 把文件写入响应体
… …
}.listen('8124')
Express Web 框架
Express 是一个简洁而灵活的Node应用框架, 提供了一系列强大特性创建各种Web应用。
网站:http://expressjs.com/
项目:https://github.com/visionmedia/express
Express建立一个应用
用Express创建一个应用只需要一条简单的命令。程序会生成一些基本目录和文件。
1. 创建一个应用(site):
> express site
目录结构(Express 3.1.0) > express myapp
create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/routes
create : myapp/routes/index.js
create : myapp/routes/user.js
create : myapp/views
create : myapp/views/layout.jade
create : myapp/views/index.jade
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.css
create : myapp/public/javascripts
create : myapp/public/images
2. 安装所需依赖
> npm install -d
3. 启动应用程序 > node app
package.json
example: {
"name": "nodeapp"
, "description": "My first Node App."
, "version": "0.0.1“
, "author": "Madhusudhan Srinivasa <[email protected]> (http://madhums.github.com)"
, "scripts": {
"start": "./node_modules/.bin/nodemon server.js"
}
, "dependencies": {
"express": "latest"
, "jade": "latest"
, "mongoose": "latest"
, "connect-mongo": "latest"
}
}
想了解更多package.json 和NPM的相关信息,请参考:
http://package.json.nodejitsu.com/
http://blog.nodejitsu.com/npm-cheatsheet
</thanks>