Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Nodejs getting-started
Search
lylijincheng
March 27, 2013
Technology
170
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Nodejs getting-started
lylijincheng
March 27, 2013
More Decks by lylijincheng
See All by lylijincheng
Grunt
lylijincheng
1
140
Other Decks in Technology
See All in Technology
「ビジネスがわかるエンジニア」とは何か?
ryooob
0
210
Lightning近況報告
kozy4324
0
220
OTel × Datadog で 「AI活用」を計測し、改善に繋げる
shihochan
2
560
Oracle AI Database@Google Cloud:サービス概要のご紹介
oracle4engineer
PRO
6
1.6k
SONiCのLinuxベースを活かしたZabbix監視
sonic
0
270
AI時代のコスト管理を考えよう〜明日から使える実践AWSノウハウ~
yoshimi0227
0
760
SONiCの統計情報を取得したい
sonic
0
270
作る力から、見極める力へ — AI時代に広がるエンジニアの価値と役割
rince
0
280
從開發到部署全都交給 AI:實作 AI 驅動的自動化流程
appleboy
0
100
IaC コードを資産へ:AWS CDK 社内ライブラリと横断展開 / aws-summit-japan-2026
gotok365
10
1.5k
コミュニティの有益性 ~JAWS Days 2026 での体験を通して~ / The Benefits of a Community ~Through My Experience at JAWS Days 2026~
seike460
PRO
0
260
徹底討論!ECS vs EKS!
daitak
3
1.3k
Featured
See All Featured
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
52
6k
Measuring & Analyzing Core Web Vitals
bluesmoon
9
870
The Anti-SEO Checklist Checklist. Pubcon Cyber Week
ryanjones
0
170
The Limits of Empathy - UXLibs8
cassininazir
1
370
Facilitating Awesome Meetings
lara
57
7k
Un-Boring Meetings
codingconduct
0
320
Documentation Writing (for coders)
carmenintech
77
5.4k
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
490
Paper Plane
katiecoart
PRO
1
52k
Typedesign – Prime Four
hannesfritz
42
3.1k
Mind Mapping
helmedeiros
PRO
1
260
Between Models and Reality
mayunak
4
350
Transcript
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>