SlideShare una empresa de Scribd logo
1 de 30
Descargar para leer sin conexión
http://techmaster.vn 
Nodes.js 
Basic 
cuong@techmaster.vn
http://techmaster.vn 
Slide tóm tắt bài lab thực hành tại Techmaster 
Để 
nắm 
vững 
kỹ 
năng 
lập 
trình 
Node.js 
bạn 
cần 
thực 
hành 
tại 
phòng 
lab 
theo 
các 
ví 
dụ 
và 
dự 
án 
cụ 
thể
http://techmaster.vn 
Nodes.js 
• Node.js 
chạy 
trên 
Chrome’s 
JavaScript 
run 
time 
V8 
https://code.google.com/p/v8-­‐wiki/ 
• Node.js 
sử 
dụng 
event 
driven, 
non-­‐blocking 
I/O 
• PHP: 
resquest 
– 
response, 
blocking 
I/O
http://techmaster.vn 
Tại sao xài Node.js? 
• Phong 
trào? 
Không, 
để 
lập 
trình 
Node 
chỉ 
cần 
JavaScript 
cả 
server 
lẫn 
client 
• Chạy 
nhanh 
hơn 
PHP, 
tốn 
ít 
RAM 
hơn 
Java 
trong 
hầu 
hết 
các 
ứng 
dụng 
• JavaScript 
dễ 
học, 
phổ 
biến. 
• Node 
module 
đa 
dạng
http://techmaster.vn
http://techmaster.vn 
Block vs Non-Blocking I/O 
hGp://blog.mixu.net/2011/02/01/understanding-­‐the-­‐node-­‐js-­‐event-­‐loop/
http://techmaster.vn
http://techmaster.vn 
Nodes 
vs 
PHP 
hGp://webapplog.com/php-­‐vs-­‐node-­‐js/
http://techmaster.vn 
Cài Node.js trên Mac 
Cách 
1: 
Sử 
dụng 
HomeBrew 
http://thechangelog.com/install-­‐node-­‐js-­‐with-­‐homebrew-­‐on-­‐os-­‐x/ 
Cách 
2: 
Tải 
bộ 
cài 
rồi 
cài 
đặt 
http://coolestguidesontheplanet.com/installing-­‐node-­‐js-­‐on-­‐ 
osx-­‐10-­‐10-­‐yosemite/
http://techmaster.vn 
Kiểm tra sau khi cài đặt 
$ which node 
/usr/local/bin/node 
$ node –v 
v0.10.33 
$ npm -v 
2.1.8
Sử dụng node để chạy JavaScript 
http://techmaster.vn 
nano helloNode.js 
var name = "Node.js"; 
console.log("Hello " + name); 
node helloNode.js 
Soạn 
thảo 
helloNode.js 
bằng 
lệnh 
nano 
hoặc 
code 
editor 
như 
SublimeText
http://techmaster.vn 
Học JavaScript trong 21 giờ
http://techmaster.vn 
Công cụ, IDE lập trình Node 
• nano, 
vim 
• Sublime 
Text, 
Text 
Wrangler, 
TextMate, 
NotePad++ 
• WebStorm, 
99$ 
đáng 
đồng 
tiền 
bát 
gạo. 
Plugins: 
Node.js, 
Spy-­‐js, 
Stylus
Cấu 
hình 
WebStorm 
hỗ 
trợ 
Node.js 
http://techmaster.vn
Vào 
đây 
xem 
chi 
cết 
ý 
nghĩa 
của 
package.json 
http://techmaster.vn 
hGp://browsenpm.org/package.json
http://techmaster.vn 
Tạo web server đơn giản 
var http = require('http');! 
http.createServer(function(req, res) {! 
res.writeHead(200, {'Content-Type': 'text/plain'});! 
res.end('Hello Worldn');! 
}).listen(3000);! 
console.log('Server is running at http://localhost:3000');!
Viết tách ra, thay var bằng const 
http://techmaster.vn 
const http = require('http');! 
! 
const server = http.createServer();! 
! 
server.on('request', function(req, res) {! 
res.writeHead(200, {'Content-Type': 'text/plain'});! 
res.end('Hello Worldn');! 
});! 
! 
server.listen(3000);! 
console.log('Server is running at http://localhost:3000');
const http = require('http'); 
Module 
đóng 
gói 
các 
hàm 
JavaScript 
hữu 
ích 
được 
export 
ra 
để 
tái 
sử 
dụng 
lại 
http://techmaster.vn 
require('module_name') trả 
về 
object 
chứa 
các 
hàm
http://techmaster.vn 
Return JSON 
var http = require('http');! 
! 
var server = http.createServer();! 
! 
server.on('request', function(req, res) {! 
res.setHeader('Content-Type', 'application/json');! 
res.writeHead(200, 'json content');! 
res.write('{"spy_agent": "OX-13"}');! 
res.end();! 
});! 
! 
server.listen(3000);! 
console.log('JSON server is running at http://localhost:3000');!
http://techmaster.vn 
Serve file 
const http = require('http');! 
const fs = require('fs');! 
const server = http.createServer();! 
server.on('request', function(req, res){! 
res.writeHead(200, {'Content-Type': 'image/jpg'});! 
fs.createReadStream('./playboy.jpg').pipe(res);! 
});! 
server.listen(3000);! 
console.log('Serve play boy at http://localhost:3000');!
route căn bản phần luồn request 
http://techmaster.vn 
var http = require('http');! 
var url = require('url');! 
! 
var server = http.createServer();! 
! 
server.on('request', function(req, res) {! 
var url_parsed = url.parse(req.url, true);! 
if (req.method === 'GET') {! 
handleGETRequest(res, url_parsed);! 
}! 
});! 
! 
server.listen(3000);
http://techmaster.vn 
handleGETRequest = function(res, url_parsed) {! 
console.log('path: ' + url_parsed.pathname);! 
switch (url_parsed.pathname) {! 
case "/":! 
res.writeHead(200, {'Content-Type': 'text/plain'});! 
res.end('Front page is heren');! 
break;! 
case "/hi":! 
res.writeHead(200, {'Content-Type': 'text/plain'});! 
res.end('Hello Worldn');! 
break;! 
case "/api":! 
res.setHeader('Content-Type', 'application/json');! 
res.writeHead(200, 'json content');! 
res.write('{"spy_agent": "OX-13"}');! 
res.end();! 
break;! 
}! 
Route 
requests 
};
Tìm tài liệu các Node.js module 
http://techmaster.vn 
file 
system 
(fs) 
à 
http://nodejs.org/api/fs.html
Lập 
trình 
web 
app 
bằng 
framework 
mới 
nhanh 
http://techmaster.vn 
được! 
Express 
!!! 
hGp://expressjs.com/
http://techmaster.vn 
Cài đặt express 
$ mkdir myapp & cd myapp 
$ npm init//Tạo 
ra 
package.json 
$ npm install express --save
npm : Notes Package Management 
http://techmaster.vn 
• Cài 
đặt 
– 
quản 
lý 
– 
phát 
hành 
các 
package 
(gói 
thư 
viện 
tái 
sử 
dụng) 
• https://www.npmjs.org/
npm : Notes Package Management 
http://techmaster.vn 
$ npm ls //liệt 
kê 
các 
package 
$ ls ~/.npm //thư 
mục 
chứa 
Nodes 
package 
ở 
/ 
Users/YourAccount/.npm 
$ npm update //Cập 
nhật 
các 
package 
mới
name: (nodeproject) NodeProject 
version: (1.0.0) 2.0.1 
description: Cuong shows how to use npm init to create package.json 
entry point: (index.js) boot.js 
test command: 
git repository: https://github.com/TechMaster 
keywords: Techmaster.vn npm init 
author: Trinh Minh Cuong 
license: (ISC) MIT 
http://techmaster.vn 
npm init
package.json là kết quả của npm init 
{ 
"name": "NodeProject", 
"version": "2.0.1", 
"description": "Cuong shows how to use npm init to create package.json", 
"main": "boot.js", 
"scripts": { 
http://techmaster.vn 
"test": "echo "Error: no test specified" && exit 1" 
}, 
"repository": { 
"type": "git", 
"url": "https://github.com/TechMaster" 
}, 
"keywords": [ 
"Techmaster.vn", 
"npm", 
"init" 
], 
"author": "Trinh Minh Cuong", 
"license": "MIT" 
}
Các 
buổi 
học 
cếp 
theo 
chúng 
ta 
sẽ 
học 
lập 
trình 
web 
site 
dùng 
Express: 
1-­‐ 
Tạo 
API 
Rest 
2-­‐ 
CRUD 
dữ 
liệu 
vào 
CSDL 
MongoDB 
hoặc 
Postgresql 
3-­‐ 
Socket.IO 
4-­‐ 
Nacve 
mobile 
app 
kết 
nối 
vào 
Socket.IO 
http://techmaster.vn

Más contenido relacionado

La actualidad más candente

Công cụ và phương pháp phát hiện lỗ hổng bảo mật web application
Công cụ và phương pháp phát hiện lỗ hổng bảo mật web applicationCông cụ và phương pháp phát hiện lỗ hổng bảo mật web application
Công cụ và phương pháp phát hiện lỗ hổng bảo mật web application
ducmanhkthd
 
Hệ PhâN TáN
Hệ PhâN TáNHệ PhâN TáN
Hệ PhâN TáN
it
 
Tim hieu lo hong web va cach phong chong
Tim hieu lo hong web va cach phong chongTim hieu lo hong web va cach phong chong
Tim hieu lo hong web va cach phong chong
Vu Trung Kien
 

La actualidad más candente (20)

Đề Tài Thiết Kế Phần Mềm Quản Lý Sinh Viên
Đề Tài Thiết Kế Phần Mềm Quản Lý Sinh Viên Đề Tài Thiết Kế Phần Mềm Quản Lý Sinh Viên
Đề Tài Thiết Kế Phần Mềm Quản Lý Sinh Viên
 
Slide 1 - Thiết kế Web cơ bản
 Slide 1 - Thiết kế Web cơ bản Slide 1 - Thiết kế Web cơ bản
Slide 1 - Thiết kế Web cơ bản
 
hệ quản trị cơ sỡ dữ liệu bán vé xem phim
hệ quản trị cơ sỡ dữ liệu bán vé xem phimhệ quản trị cơ sỡ dữ liệu bán vé xem phim
hệ quản trị cơ sỡ dữ liệu bán vé xem phim
 
Công cụ và phương pháp phát hiện lỗ hổng bảo mật web application
Công cụ và phương pháp phát hiện lỗ hổng bảo mật web applicationCông cụ và phương pháp phát hiện lỗ hổng bảo mật web application
Công cụ và phương pháp phát hiện lỗ hổng bảo mật web application
 
Bài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
Bài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theoBài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
Bài 1: Làm quen với ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
 
Đồ án thực tập cơ sở các kĩ thuật tấn công SQL injection và cách phòng chống
Đồ án thực tập cơ sở các kĩ thuật tấn công SQL injection và cách phòng chốngĐồ án thực tập cơ sở các kĩ thuật tấn công SQL injection và cách phòng chống
Đồ án thực tập cơ sở các kĩ thuật tấn công SQL injection và cách phòng chống
 
400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2
400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2
400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2
 
API Testing & SoapUI
API Testing & SoapUIAPI Testing & SoapUI
API Testing & SoapUI
 
Hệ PhâN TáN
Hệ PhâN TáNHệ PhâN TáN
Hệ PhâN TáN
 
Bài tập HTML/CSS
Bài tập HTML/CSSBài tập HTML/CSS
Bài tập HTML/CSS
 
Báo cáo SQL injecttion
Báo cáo SQL injecttionBáo cáo SQL injecttion
Báo cáo SQL injecttion
 
Lập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHPLập trình hướng đối tượng trong PHP
Lập trình hướng đối tượng trong PHP
 
Câu hỏi trắc nghiệm PHP
Câu hỏi trắc nghiệm PHPCâu hỏi trắc nghiệm PHP
Câu hỏi trắc nghiệm PHP
 
Bài giảng thiết kế website - truongkinhtethucpham.com
Bài giảng thiết kế website - truongkinhtethucpham.comBài giảng thiết kế website - truongkinhtethucpham.com
Bài giảng thiết kế website - truongkinhtethucpham.com
 
Phân tích và thiết kế hệ thống quản lý bán hàng
Phân tích và thiết kế hệ thống quản lý bán hàngPhân tích và thiết kế hệ thống quản lý bán hàng
Phân tích và thiết kế hệ thống quản lý bán hàng
 
Tim hieu lo hong web va cach phong chong
Tim hieu lo hong web va cach phong chongTim hieu lo hong web va cach phong chong
Tim hieu lo hong web va cach phong chong
 
Bài giảng Công Nghệ Phần Mềm
Bài giảng Công Nghệ Phần MềmBài giảng Công Nghệ Phần Mềm
Bài giảng Công Nghệ Phần Mềm
 
Đề tài: Xây dựng website giới thiệu sản phẩm phần mềm, HOT
Đề tài: Xây dựng website giới thiệu sản phẩm phần mềm, HOTĐề tài: Xây dựng website giới thiệu sản phẩm phần mềm, HOT
Đề tài: Xây dựng website giới thiệu sản phẩm phần mềm, HOT
 
Bài 7 Xây dựng website sử dụng PHP và MySQL - Giáo trình FPT
Bài 7 Xây dựng website sử dụng PHP và MySQL - Giáo trình FPTBài 7 Xây dựng website sử dụng PHP và MySQL - Giáo trình FPT
Bài 7 Xây dựng website sử dụng PHP và MySQL - Giáo trình FPT
 
Xây dựng cơ sở dữ liệu trong quản lý nhân sự
Xây dựng cơ sở dữ liệu trong quản lý nhân sựXây dựng cơ sở dữ liệu trong quản lý nhân sự
Xây dựng cơ sở dữ liệu trong quản lý nhân sự
 

Destacado

Nodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioNodejs introduce - using Socket.io
Nodejs introduce - using Socket.io
Caesar Chi
 

Destacado (20)

Tìm hiểu về NodeJs
Tìm hiểu về NodeJsTìm hiểu về NodeJs
Tìm hiểu về NodeJs
 
Authentication and Authorization
Authentication and AuthorizationAuthentication and Authorization
Authentication and Authorization
 
Tìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tớiTìm nền tảng lập trình cho 5 năm tới
Tìm nền tảng lập trình cho 5 năm tới
 
Postgresql security
Postgresql securityPostgresql security
Postgresql security
 
Cấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phútCấu hình Postgresql căn bản trong 20 phút
Cấu hình Postgresql căn bản trong 20 phút
 
Postgresql các vấn đề thực tế
Postgresql các vấn đề thực tếPostgresql các vấn đề thực tế
Postgresql các vấn đề thực tế
 
Cơ sở dữ liệu postgres
Cơ sở dữ liệu postgresCơ sở dữ liệu postgres
Cơ sở dữ liệu postgres
 
Nodejs introduce - using Socket.io
Nodejs introduce - using Socket.ioNodejs introduce - using Socket.io
Nodejs introduce - using Socket.io
 
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
ITLC - Hanoi - NodeJS - ArrowJS - 27-11 - 2015
 
Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907Node Foundation Membership Overview 20160907
Node Foundation Membership Overview 20160907
 
Analyze and Visualize Git Log for Fun and Profit - DevTernity 2015
Analyze and Visualize Git Log for Fun and Profit - DevTernity 2015Analyze and Visualize Git Log for Fun and Profit - DevTernity 2015
Analyze and Visualize Git Log for Fun and Profit - DevTernity 2015
 
Making a living
Making a livingMaking a living
Making a living
 
Phalcon căn bản
Phalcon căn bảnPhalcon căn bản
Phalcon căn bản
 
Phalcon introduction
Phalcon introductionPhalcon introduction
Phalcon introduction
 
Prototyping giao diện sử dụng Expression Blend Sketch Flow
Prototyping giao diện sử dụng Expression Blend Sketch FlowPrototyping giao diện sử dụng Expression Blend Sketch Flow
Prototyping giao diện sử dụng Expression Blend Sketch Flow
 
Minimum Viable Products
Minimum Viable ProductsMinimum Viable Products
Minimum Viable Products
 
iOS Master - Detail & TabBar
iOS Master - Detail & TabBariOS Master - Detail & TabBar
iOS Master - Detail & TabBar
 
Slide that wins
Slide that winsSlide that wins
Slide that wins
 
Bài trình bày cho sinh viên Bách Khoa 9/2012
Bài trình bày cho sinh viên Bách Khoa 9/2012Bài trình bày cho sinh viên Bách Khoa 9/2012
Bài trình bày cho sinh viên Bách Khoa 9/2012
 
Spring MVC - Web Forms
Spring MVC  - Web FormsSpring MVC  - Web Forms
Spring MVC - Web Forms
 

Similar a Node.js căn bản

Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952
Ham Chơi
 
Web course php co ban
Web course   php co banWeb course   php co ban
Web course php co ban
慂 志慂
 

Similar a Node.js căn bản (20)

Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSXHướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
Hướng dẫn sử dụng CocoaPods trong dự án iOS hoặc MacOSX
 
Arrowjs.io
Arrowjs.ioArrowjs.io
Arrowjs.io
 
Asp control
Asp controlAsp control
Asp control
 
Giới thiệu Nuxt.js
Giới thiệu Nuxt.jsGiới thiệu Nuxt.js
Giới thiệu Nuxt.js
 
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
Lập trình background job bằng azurequeue và webjob sử dụng azure storage emul...
 
Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952
 
Apache+ q logs
Apache+ q logsApache+ q logs
Apache+ q logs
 
Lập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biếnLập trình web với các công nghệ phổ biến
Lập trình web với các công nghệ phổ biến
 
Báo cáo tuần đồ án
Báo cáo tuần đồ ánBáo cáo tuần đồ án
Báo cáo tuần đồ án
 
Dsd05 02a-xml-rpca
Dsd05 02a-xml-rpcaDsd05 02a-xml-rpca
Dsd05 02a-xml-rpca
 
Giáo trình asp.net với c sharp
Giáo trình asp.net với c sharpGiáo trình asp.net với c sharp
Giáo trình asp.net với c sharp
 
07 web course 1 php co ban
07 web course   1 php co ban07 web course   1 php co ban
07 web course 1 php co ban
 
Technical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vnTechnical note playframework_documentation_working with play - java_vn
Technical note playframework_documentation_working with play - java_vn
 
Ch06
Ch06Ch06
Ch06
 
Bai th08 php voi csdl
Bai th08 php voi csdlBai th08 php voi csdl
Bai th08 php voi csdl
 
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
[DevDay2019] Develop a web application with Kubernetes - By Nguyen Xuan Phong...
 
Go micro framework to build microservices
Go micro framework to build microservicesGo micro framework to build microservices
Go micro framework to build microservices
 
Web course php co ban
Web course   php co banWeb course   php co ban
Web course php co ban
 
Lesson 1 practice
Lesson 1 practiceLesson 1 practice
Lesson 1 practice
 
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cậnTrần Anh Khoa - Kautilya và Powershelltrong kỹ thuật tấn công tiếp cận
Trần Anh Khoa - Kautilya và Powershell trong kỹ thuật tấn công tiếp cận
 

Más de TechMaster Vietnam

Chương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMaster
Chương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMasterChương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMaster
Chương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMaster
TechMaster Vietnam
 

Más de TechMaster Vietnam (13)

Neural Network from Scratch
Neural Network from ScratchNeural Network from Scratch
Neural Network from Scratch
 
Flutter vs React Native 2018
Flutter vs React Native 2018Flutter vs React Native 2018
Flutter vs React Native 2018
 
C đến C++ phần 1
C đến C++ phần 1C đến C++ phần 1
C đến C++ phần 1
 
Control structure in C
Control structure in CControl structure in C
Control structure in C
 
Basic C programming
Basic C programmingBasic C programming
Basic C programming
 
Knex Postgresql Migration
Knex Postgresql MigrationKnex Postgresql Migration
Knex Postgresql Migration
 
Chia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTTChia sẻ kinh nghiệm giảng dạy CNTT
Chia sẻ kinh nghiệm giảng dạy CNTT
 
Manage your project differently
Manage your project differentlyManage your project differently
Manage your project differently
 
Day0: Giới thiệu lập trình ứng dụng Apple iOS
Day0: Giới thiệu lập trình ứng dụng Apple iOSDay0: Giới thiệu lập trình ứng dụng Apple iOS
Day0: Giới thiệu lập trình ứng dụng Apple iOS
 
Chương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMaster
Chương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMasterChương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMaster
Chương trình thực tập chuyên sâu dành cho học viên khóa iOS tại TechMaster
 
Apple iOS Memory Management - Vietnamese version
Apple iOS Memory Management - Vietnamese versionApple iOS Memory Management - Vietnamese version
Apple iOS Memory Management - Vietnamese version
 
Sinh viên CNTT làm gì trong 5 năm tới
Sinh viên CNTT làm gì trong 5 năm tớiSinh viên CNTT làm gì trong 5 năm tới
Sinh viên CNTT làm gì trong 5 năm tới
 
Windows 8 vs android 4
Windows 8 vs android 4Windows 8 vs android 4
Windows 8 vs android 4
 

Node.js căn bản

  • 2. http://techmaster.vn Slide tóm tắt bài lab thực hành tại Techmaster Để nắm vững kỹ năng lập trình Node.js bạn cần thực hành tại phòng lab theo các ví dụ và dự án cụ thể
  • 3. http://techmaster.vn Nodes.js • Node.js chạy trên Chrome’s JavaScript run time V8 https://code.google.com/p/v8-­‐wiki/ • Node.js sử dụng event driven, non-­‐blocking I/O • PHP: resquest – response, blocking I/O
  • 4. http://techmaster.vn Tại sao xài Node.js? • Phong trào? Không, để lập trình Node chỉ cần JavaScript cả server lẫn client • Chạy nhanh hơn PHP, tốn ít RAM hơn Java trong hầu hết các ứng dụng • JavaScript dễ học, phổ biến. • Node module đa dạng
  • 6. http://techmaster.vn Block vs Non-Blocking I/O hGp://blog.mixu.net/2011/02/01/understanding-­‐the-­‐node-­‐js-­‐event-­‐loop/
  • 8. http://techmaster.vn Nodes vs PHP hGp://webapplog.com/php-­‐vs-­‐node-­‐js/
  • 9. http://techmaster.vn Cài Node.js trên Mac Cách 1: Sử dụng HomeBrew http://thechangelog.com/install-­‐node-­‐js-­‐with-­‐homebrew-­‐on-­‐os-­‐x/ Cách 2: Tải bộ cài rồi cài đặt http://coolestguidesontheplanet.com/installing-­‐node-­‐js-­‐on-­‐ osx-­‐10-­‐10-­‐yosemite/
  • 10. http://techmaster.vn Kiểm tra sau khi cài đặt $ which node /usr/local/bin/node $ node –v v0.10.33 $ npm -v 2.1.8
  • 11. Sử dụng node để chạy JavaScript http://techmaster.vn nano helloNode.js var name = "Node.js"; console.log("Hello " + name); node helloNode.js Soạn thảo helloNode.js bằng lệnh nano hoặc code editor như SublimeText
  • 13. http://techmaster.vn Công cụ, IDE lập trình Node • nano, vim • Sublime Text, Text Wrangler, TextMate, NotePad++ • WebStorm, 99$ đáng đồng tiền bát gạo. Plugins: Node.js, Spy-­‐js, Stylus
  • 14. Cấu hình WebStorm hỗ trợ Node.js http://techmaster.vn
  • 15. Vào đây xem chi cết ý nghĩa của package.json http://techmaster.vn hGp://browsenpm.org/package.json
  • 16. http://techmaster.vn Tạo web server đơn giản var http = require('http');! http.createServer(function(req, res) {! res.writeHead(200, {'Content-Type': 'text/plain'});! res.end('Hello Worldn');! }).listen(3000);! console.log('Server is running at http://localhost:3000');!
  • 17. Viết tách ra, thay var bằng const http://techmaster.vn const http = require('http');! ! const server = http.createServer();! ! server.on('request', function(req, res) {! res.writeHead(200, {'Content-Type': 'text/plain'});! res.end('Hello Worldn');! });! ! server.listen(3000);! console.log('Server is running at http://localhost:3000');
  • 18. const http = require('http'); Module đóng gói các hàm JavaScript hữu ích được export ra để tái sử dụng lại http://techmaster.vn require('module_name') trả về object chứa các hàm
  • 19. http://techmaster.vn Return JSON var http = require('http');! ! var server = http.createServer();! ! server.on('request', function(req, res) {! res.setHeader('Content-Type', 'application/json');! res.writeHead(200, 'json content');! res.write('{"spy_agent": "OX-13"}');! res.end();! });! ! server.listen(3000);! console.log('JSON server is running at http://localhost:3000');!
  • 20. http://techmaster.vn Serve file const http = require('http');! const fs = require('fs');! const server = http.createServer();! server.on('request', function(req, res){! res.writeHead(200, {'Content-Type': 'image/jpg'});! fs.createReadStream('./playboy.jpg').pipe(res);! });! server.listen(3000);! console.log('Serve play boy at http://localhost:3000');!
  • 21. route căn bản phần luồn request http://techmaster.vn var http = require('http');! var url = require('url');! ! var server = http.createServer();! ! server.on('request', function(req, res) {! var url_parsed = url.parse(req.url, true);! if (req.method === 'GET') {! handleGETRequest(res, url_parsed);! }! });! ! server.listen(3000);
  • 22. http://techmaster.vn handleGETRequest = function(res, url_parsed) {! console.log('path: ' + url_parsed.pathname);! switch (url_parsed.pathname) {! case "/":! res.writeHead(200, {'Content-Type': 'text/plain'});! res.end('Front page is heren');! break;! case "/hi":! res.writeHead(200, {'Content-Type': 'text/plain'});! res.end('Hello Worldn');! break;! case "/api":! res.setHeader('Content-Type', 'application/json');! res.writeHead(200, 'json content');! res.write('{"spy_agent": "OX-13"}');! res.end();! break;! }! Route requests };
  • 23. Tìm tài liệu các Node.js module http://techmaster.vn file system (fs) à http://nodejs.org/api/fs.html
  • 24. Lập trình web app bằng framework mới nhanh http://techmaster.vn được! Express !!! hGp://expressjs.com/
  • 25. http://techmaster.vn Cài đặt express $ mkdir myapp & cd myapp $ npm init//Tạo ra package.json $ npm install express --save
  • 26. npm : Notes Package Management http://techmaster.vn • Cài đặt – quản lý – phát hành các package (gói thư viện tái sử dụng) • https://www.npmjs.org/
  • 27. npm : Notes Package Management http://techmaster.vn $ npm ls //liệt kê các package $ ls ~/.npm //thư mục chứa Nodes package ở / Users/YourAccount/.npm $ npm update //Cập nhật các package mới
  • 28. name: (nodeproject) NodeProject version: (1.0.0) 2.0.1 description: Cuong shows how to use npm init to create package.json entry point: (index.js) boot.js test command: git repository: https://github.com/TechMaster keywords: Techmaster.vn npm init author: Trinh Minh Cuong license: (ISC) MIT http://techmaster.vn npm init
  • 29. package.json là kết quả của npm init { "name": "NodeProject", "version": "2.0.1", "description": "Cuong shows how to use npm init to create package.json", "main": "boot.js", "scripts": { http://techmaster.vn "test": "echo "Error: no test specified" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/TechMaster" }, "keywords": [ "Techmaster.vn", "npm", "init" ], "author": "Trinh Minh Cuong", "license": "MIT" }
  • 30. Các buổi học cếp theo chúng ta sẽ học lập trình web site dùng Express: 1-­‐ Tạo API Rest 2-­‐ CRUD dữ liệu vào CSDL MongoDB hoặc Postgresql 3-­‐ Socket.IO 4-­‐ Nacve mobile app kết nối vào Socket.IO http://techmaster.vn