SlideShare a Scribd company logo
Node.js :: Introduction — Part 2
PLAN
Node.js
Frameworks	&	Libs
Demo	application
NODE.JS
																																														is	bad	for:
CPU	heavy	tasks
Doing	everything	with	Node
NODE.JS
																																																											is	good	for:
Prototyping
REST	/	JSON	APIs
SPA
Streaming	data
Real-time	apps
MODULES
Node	Package	Manager

~55k	modules	available
NPM
	npm	install	express
	npm	install	express	-g
	npm	install	express	--save
	npm	install	nodemon	--save-dev
PACKAGE.JSON
	{
		"name":	"application-name",
		"version":	"0.0.1",
		"private":	true,
		"scripts":	{
				"start":	"node	app.js"
		},
		"dependencies":	{
				"express":	"3.4.8",
				"jade":	"*"
		},
		"devDependencies:	{
		}
	}
	npm	publish	<tarball>
	npm	publish	<folder>
HTTP	SERVER
	var	http	=	require('http');
	http.createServer(function	(req,	res)	{
			res.writeHead(200,	{'Content-Type':	'text/plain'});
			res.end('Hello	World!');
	}).listen(3000);
	node	server.js
WHAT'S	INSIDE
HTTP,	HTTPS	&	TCP	interfaces
File	System	I/O
Streams
Child	Process
Cluster
.	.	.
NETWORK	INTERFACES
HTTP/HTTPS/TCP
	//	require	a	module
	var	server	=	http	||	https	||	net;
	server.createServer([requestListener]).listen(port,	[callback]);
FILE	SYSTEM	I/O
	var	fs	=	require('fs');
	fs.readFile(filename,	[options],	callback);
	fs.readFileSync(filename,	[options]);
	fs.writeFile(filename,	data,	[options],	callback);
	fs.writeFileSync(filename,	data,	[options]);
	fs.rmdir(path,	callback);
	fs.unlink(path,	callback);
	fs.readdir(path,	callback);
STREAMS
Readable	(req,	fs,	stdout,	stderr)
Writable	(res,	fs,	stdin)
Duplex	(TCP	sockets,	crypto)
Transform	(zlib,	crypto)
STREAMS	USE	CASE
	http.createServer(function	(req,	res)	{
			fs.readFile(__dirname	+	'/file.txt',	function	(err,	data)	{
					res.end(data);
			});
	});

VS
	http.createServer(function	(req,	res)	{
			var	stream	=	fs.createReadStream(__dirname	+	'/file.txt');
			stream.pipe(res);
	});
CHILD	PROCESS
	var	cp	=	require('child_process');
	cp.spawn(command,	[args],	[options]);
	cp.exec(command,	[options],	callback);
	cp.execFile(file,	[args],	[options],	[callback]);
	cp.fork(modulePath,	[args],	[options]);
	child.stdin		//	Writable	stream
	child.stdout	//	Readable	stream
	child.stderr	//	Readable	stream
	//	Sync,	used	with	'forked'	process	only
	child.send(message);
	child.on('message',	callback);
CLUSTER
	var	cluster	=	require('cluster'),
					http	=	require('http'),
					numCPUs	=	require('os').cpus().length;
	if	(cluster.isMaster)	{
			for	(var	i	=	0;	i	<	numCPUs;	i++)	{
					cluster.fork();
			}
	}	else	{
			http.createServer(function	(req,	res)	{
					res.writeHead(200,	{'Content-Type':	'text/plain'});
					res.end('Hello	World!');
			}).listen(3000);
	}
PROTOTYPING
MEAN	STACK
MongoDB	+	Express	+	AngularJS	+	Node.js

	

mean.io
EXPRESS
Middleware	system
Router
Templating	(Jade,	EJS)
	npm	install	-g	express
	express	appname
SETTING	UP
	var	express	=	require('express'),
					app	=	express();
	app.set('port',	process.env.PORT	||	3000);
	app.set('view	engine',	'jade');
	app.set('views',	__dirname	+	'/views');
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	app.use(express.static(path.join(__dirname,	'public')));
	app.listen(app.get('port'));
MIDDLEWARES
	app.use(function	(req,	res,	next)	{
		//	Do	something...
		next();	//	Call	next	middleware
	});
var	middleware	=	function	(req,	res,	next)	{
		//	Do	something...
		next();	//	Call	next	middleware
};
ROUTES
	app.get('/',	function	(req,	res)	{
			res.render('index');
	});
	app.get('/user',	middleware,	function	(req,	res)	{
			res.render('user');	//	Render	page	for	authorized	users	only
	});
ERROR	HANDLING
CUSTOM	ERRORS
	var	AuthError	=	function	(msg)	{
			Error.call(this);
			Error.captureStackTrace(this,	arguments.callee);
			this.message	=	msg;
			this.name	=	'AuthError';
	};
	AuthError.prototype.__proto__	=	Error.prototype;
ERROR	HANDLING
ERROR	MIDDLEWARE
	app.use(function	(err,	req,	res,	next)	{
			if	(err.name	==	'AuthError')	{
					res.send(401,	{error:	err.message});
			}
	});
	var	middleware	=	function	(req,	res,	next)	{
			if	(req.body.password	!=	'password')	{
					return	next(new	AuthError('Unauthorized'));
			}
			next();
	};
MONGODB
Document-Oriented	BSON	data	storage
+	Mongoose	ODM
	var	mongoose	=	require('mongoose');
	mongoose.connect('mongodb://localhost/dbname');
MONGOOSE	SCHEMAS
	var	Schema	=	require('mongoose').Schema;
	var	UserSchema	=	new	Schema({
			username:	{
					type:	String,
					unique:	true,
					required:	true
			},
			comments:	[{body:	String,	date:	Date}],
			modified:	{
					type:	Date,
					default:	Date.now
			},
			role:	String
	});
	var	User	=	mongoose.model('User',	UserSchema);
CRUD
	var	user	=	new	User(data);
	user.save(function	(err,	user)	{});
	User.find(function	(err,	users)	{});
	User.find({role:	'Moderator'},	function	(err,	users)	{});
	User.findOne({username:	'user'},	function	(err,	user)	{});
	User.findById(id,	function	(err,	user)	{
			user.remove(function	(err)	{});
	});
JSON/REST	API
	app.post('/books',	function	(req,	res,	next)	{
			var	book	=	new	Book(req.body);
			book.save(function	(err,	book)	{
					if	(err)	return	next(new	Error('Server	error'));
					res.send(200,	{book:	book});
			});
	});
	app.get('/books/:id',	function	(req,	res,	next)	{
			Book.findById(req.params.id,	function	(err,	book)	{
					if	(err)	return	next(new	Error('Server	error'));
					if	(!book)	return	res.send(404,	{error:	'Not	found'});
					res.send(200,	{book:	book});
			});
	});
	//	...
REAL-TIME
SOCKET.IO
	var	io	=	require('socket.io').listen(80);
	io.sockets.on('connection',	function	(socket)	{
			socket.on('my	event',	function	(data)	{});
			socket.emit('another	event',	data);
	});
DEMO	TIME
WHAT	ELSE?
Forever
Nodemon
Node-Inspect
Meteor
JXcore
CLI
Front-end	tools
LINKS
nodejs.org/api
github.com/substack/stream-handbook
nodestreams.com
howtonode.org
nodeschool.io
github.com/roman01la/RTVideo

More Related Content

PDF
All aboard the NodeJS Express
PPTX
Node.js in a heterogeneous system
PPTX
Herramientas front
PDF
Non-blocking I/O, Event loops and node.js
PDF
PDF
Java/Spring과 Node.js의 공존 시즌2
PDF
Ansible
PDF
Warsztaty ansible
All aboard the NodeJS Express
Node.js in a heterogeneous system
Herramientas front
Non-blocking I/O, Event loops and node.js
Java/Spring과 Node.js의 공존 시즌2
Ansible
Warsztaty ansible

What's hot (20)

PPT
Building your first Node app with Connect & Express
PDF
Node.js in a heterogeneous system
PDF
Webconf nodejs-production-architecture
PDF
Nodejs vatsal shah
PDF
Introduction to Node.js: What, why and how?
PDF
[Js hcm] Deploying node.js with Forever.js and nginx
PDF
KEY
Writing robust Node.js applications
PDF
(WS14) Sasa Matijasic - Node.js i "novi" web
PPTX
Introduction to Node.js
KEY
Building HTTP API's with NodeJS and MongoDB
PPTX
introduction to node.js
PPT
RESTful API In Node Js using Express
PPTX
Node js introduction
PDF
Npm: beyond 'npm i'
PDF
Software Tests with MongoDB
KEY
Introduction to node.js
PPTX
Introduction to Node js
PPTX
Java script at backend nodejs
PPTX
Introduction to node.js GDD
Building your first Node app with Connect & Express
Node.js in a heterogeneous system
Webconf nodejs-production-architecture
Nodejs vatsal shah
Introduction to Node.js: What, why and how?
[Js hcm] Deploying node.js with Forever.js and nginx
Writing robust Node.js applications
(WS14) Sasa Matijasic - Node.js i "novi" web
Introduction to Node.js
Building HTTP API's with NodeJS and MongoDB
introduction to node.js
RESTful API In Node Js using Express
Node js introduction
Npm: beyond 'npm i'
Software Tests with MongoDB
Introduction to node.js
Introduction to Node js
Java script at backend nodejs
Introduction to node.js GDD
Ad

Similar to Node.js :: Introduction — Part 2 (20)

PPTX
Introduction to node.js by jiban
KEY
Introduction to NodeJS with LOLCats
PDF
Node intro
PPTX
Introduction to node.js By Ahmed Assaf
PPTX
ODP
Introduce about Nodejs - duyetdev.com
PPTX
Intro to Node.js (v1)
PDF
Introduction to Node.js
PPTX
Unit 1 Express J for mean stack and mern
PPT
Node js beginner
PDF
Server Side Apocalypse, JS
PPTX
NodeJS - Server Side JS
PPTX
Starting with Node.js
PPTX
Introducing Node.js in an Oracle technology environment (including hands-on)
PDF
Jaap : node, npm & grunt
PPTX
Introduction to Node (15th May 2017)
PPT
Exploring Node.jS
PDF
Node.js 101 with Rami Sayar
PPTX
Kalp Corporate Node JS Perfect Guide
KEY
Node.js - The New, New Hotness
Introduction to node.js by jiban
Introduction to NodeJS with LOLCats
Node intro
Introduction to node.js By Ahmed Assaf
Introduce about Nodejs - duyetdev.com
Intro to Node.js (v1)
Introduction to Node.js
Unit 1 Express J for mean stack and mern
Node js beginner
Server Side Apocalypse, JS
NodeJS - Server Side JS
Starting with Node.js
Introducing Node.js in an Oracle technology environment (including hands-on)
Jaap : node, npm & grunt
Introduction to Node (15th May 2017)
Exploring Node.jS
Node.js 101 with Rami Sayar
Kalp Corporate Node JS Perfect Guide
Node.js - The New, New Hotness
Ad

Recently uploaded (20)

PDF
Zenith AI: Advanced Artificial Intelligence
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
Hybrid model detection and classification of lung cancer
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PPTX
TLE Review Electricity (Electricity).pptx
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
Architecture types and enterprise applications.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Getting Started with Data Integration: FME Form 101
PPTX
observCloud-Native Containerability and monitoring.pptx
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Zenith AI: Advanced Artificial Intelligence
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Enhancing emotion recognition model for a student engagement use case through...
Web App vs Mobile App What Should You Build First.pdf
Univ-Connecticut-ChatGPT-Presentaion.pdf
O2C Customer Invoices to Receipt V15A.pptx
Hybrid model detection and classification of lung cancer
A contest of sentiment analysis: k-nearest neighbor versus neural network
TLE Review Electricity (Electricity).pptx
NewMind AI Weekly Chronicles – August ’25 Week III
Getting started with AI Agents and Multi-Agent Systems
Architecture types and enterprise applications.pdf
Programs and apps: productivity, graphics, security and other tools
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Group 1 Presentation -Planning and Decision Making .pptx
NewMind AI Weekly Chronicles - August'25-Week II
Getting Started with Data Integration: FME Form 101
observCloud-Native Containerability and monitoring.pptx
cloud_computing_Infrastucture_as_cloud_p
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf

Node.js :: Introduction — Part 2