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
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
lylijincheng
March 27, 2013
Technology
180
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
150
Other Decks in Technology
See All in Technology
Digital Credentials API × OpenID4VP ブラウザ完結型本人確認の実装知見(OAuth/OIDC Numa (Immersion) Workshop 2026)
oidfj
PRO
0
360
1.5時間を無駄にして学んだwsl2におけるaptとsnapの選択と仕組み
yosaka0123
0
470
あなたの知らないバージョン命名規則
sat
PRO
2
860
医療の現場を変革に挑戦した半年間の軌跡 - PythonとAIで現場を変える / From Code to Care
soudai
PRO
1
640
エージェント化するAI:現在地とその先に起きる変化 / AI as Agents: The Current State and the Changes Ahead
ks91
PRO
0
170
Eight Engineering Unit 紹介資料
sansan33
PRO
3
8.3k
Windows の互換機能 - 古いプログラムはなぜ動作できるのか
murachiakira
PRO
0
130
Contract One Engineering Unit 紹介資料
sansan33
PRO
0
20k
When Token Pruning is Worse than Random: Understanding Visual Token Information in VLLMs
sansantech
PRO
0
160
本番に近いテストをもっと手軽に - Postmanで広がるAPIテストの世界 / Expanding the World of API Testing with Postman
yokawasa
1
150
IHV like なユースケースへのOpenID Connect 関連仕様の適用事例
optim
0
380
dbt in Microsoft Fabric
ryomaru0825
0
300
Featured
See All Featured
Exploring the Power of Turbo Streams & Action Cable | RailsConf2023
kevinliebholz
37
6.6k
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
560
How to Get Subject Matter Experts Bought In and Actively Contributing to SEO & PR Initiatives.
livdayseo
0
180
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
35
2.8k
Dominate Local Search Results - an insider guide to GBP, reviews, and Local SEO
greggifford
PRO
0
310
Reality Check: Gamification 10 Years Later
codingconduct
0
2.3k
Highjacked: Video Game Concept Design
rkendrick25
PRO
1
450
Context Engineering - Making Every Token Count
addyosmani
9
1.1k
Mobile First: as difficult as doing things right
swwweet
225
10k
Redefining SEO in the New Era of Traffic Generation
szymonslowik
1
400
Ethics towards AI in product and experience design
skipperchong
2
350
For a Future-Friendly Web
brad_frost
183
10k
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>