More Related Content
Similar to Node getting-started
Similar to Node getting-started (20)
Node getting-started
- 5. 最简单的服务器
app.js:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).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/
- 8. 核心模块
• EventEmitter 模块
• HTTP(S) 模块
• File System 文件系统模块
• Utilities 实用对象模块:
util.inherits(constructor, super),
util.isArray(object), ...
• Socket, Stream 模块
• 全局(global) 对象:
process, Buffer, …
- 10. 创建 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 删除一个用户
- 13. 定义数据模型和实例
定义数据模型:
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']
});
- 18. 示例:创建一个文件服务器
所需模块:
• http, 创建服务器并监听请求
• path, 处理文件和路径
• fs, 提供文件系统读写等常用操作
http.createServer(function(req, res) {
// 当一个请求发生时,解析请求的URL确定文件的位置
// 检查并确认此文件的存在性
// 如果文件不存在作出相应的响应
// 如果文件存在,打开后读取数据
// 准备一个响应头
// 把文件写入响应体
… …
}.listen('8124')
- 19. Express Web 框架
Express 是一个简洁而灵活的Node应用框架, 提供了一系列
强大特性创建各种Web应用。
网站:http://expressjs.com/
项目:https://github.com/visionmedia/express
- 21. 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
- 23. package.json
example:
{
"name": "nodeapp"
, "description": "My first Node App."
, "version": "0.0.1“
, "author": "Madhusudhan Srinivasa <madhums8@gmail.com> (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