SlideShare a Scribd company logo
1 of 29
Download to read offline
Introduction to buildREST API with
WhatisNode.js ? 
«Aplatform built onChrome's JavaScript runtime for easily building fast, scalable network applications.» http://nodejs.org/ 
Node.js isneithera server nora web framework
About Node.js 
•Createdby Ryan Dahl in 2009 
•Development and maintenance sponsored byJoyent 
•LicenceMIT 
•Last release : 0.10.31 
•Based on Google V8 Engine 
•+99 000 packages
Successstories 
Rails to Node 
« Servers were cut to 3 from 30 » 
« Running up to 20x faster in some scenarios » 
« Frontend and backend mobile teams could be combined […] » 
Java to Node 
« Built almost twice as fast with fewer people » 
« Double the requests per second » 
« 35% decrease in the average response time »
Architecture 
•Single Threaded 
•Event Loop 
•Non-blockingI/O 
•Javascript(Event DrivenLanguage)
Inside Node.js 
Standard JavaScript with 
•Buffer 
•C/C++ Addons 
•Child Processes 
•Cluster 
•Console 
•Crypto 
•Debugger 
•DNS 
•Domain 
•Events 
•File System 
•Globals 
•HTTP 
•HTTPS 
•Modules 
•Net 
•OS 
•Path 
•Process 
•Punycode 
•QueryStrings 
•Readline 
•REPL 
•Stream 
•String Decoder 
•Timers 
•TLS/SSL 
•TTY 
•UDP/Datagram 
•URL 
•Utilities 
•VM 
•ZLIB 
… but withoutDOM manipulation
File package.json 
Project informations 
•Name 
•Version 
•Dependencies 
•Licence 
•Main file 
•Etc...
NPM (NodePackagedModules) 
•Findpackages : https://www.npmjs.org/ 
•Help : npm-l 
•Createpackage.json: npminit 
•Install package : 
•npminstallexpress 
•npminstallmongosse--save 
•npminstall-g mocha 
•npm installgrunt--save-dev 
•Update project from package.json 
•npm install 
•npm update
Hello Node.js 
console.log("Hello World !"); 
hello.js 
> nodehello.js 
Hello World !
Loadmodule 
•Coremodule : var http = require('http'); 
•Project file module : var mymodule= require(‘./module’); // ./module.js or ./module/index.js var mymodule= require(‘../module.js’); var mymodule= require(‘/package.json’); 
•Packagedmodule (in node_modulesdirectory): var express = require(‘express’);
Createmodule 1/2 
var PI = Math.PI; 
exports.area= function(r) { 
return PI * r * r; 
}; 
var circle= require('./circle.js'); 
console.log('The area of a circle of radius 4 is '+ circle.area(4)); 
circle.js
Createmodule 2/2 
var PI = Math.PI; 
module.exports= function(r) { 
return PI * r * r; 
}; 
var circleArea= require('./circle-area.js'); 
console.log('The area of a circle of radius 4 is '+ circleArea(4)); 
circle-area.js
Node.js 
Talk is cheapShow me the code
Express introduction 
«Fast, unopinionated, minimalist web framework forNode.js» http://expressjs.com
Express sample 
var express = require('express'); 
var app= express(); 
app.get('/', function(req, res) { 
res.send('Hello World!'); 
}); 
app.post('/:name', function (req, res) { 
res.send('Hello !'+req.param('name')); 
}); 
app.listen(3000);
Express middleware 
Middleware can: 
•Execute any code. 
•Make changes to the request and the response objects. 
•End the request-response cycle. 
•Call the next middleware in the stack. 
var express = require('express'); 
var app= express(); 
var cookieParser= require('cookie-parser'); 
app.use(express.static(__dirname+ '/public')); 
app.use(cookieParser()); 
…
Express middleware modules 
Module 
Description 
morgan 
HTTP request logger middleware for node.js 
express.static 
Serve static content from the "public" directory (js, css, html, image, video, …) 
body-parser 
Parserequestbody and populatereq.body(ie: parsejsonbody) 
cookie-parser 
Parse cookie header and populate req.cookieswith an object keyed by the cookie names 
cookie-session 
Provide "guest" sessions, meaning any visitor will have a session, authenticated or not. 
express-session 
Providegenericsession functionality within-memorystorage by default 
method-override 
Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. 
csurf 
Node.js CSRF protection middleware. 
…
Express router 
var express = require('express'); 
var router = express.Router(); 
router.get('/', function(req, res) { 
res.send('Hello World!'); 
}); 
router.post('/:name', function(req, res) { 
res.send('Hello !'+req.param('name')); 
}); 
var app= express(); 
app.use('/api/', router);
Express 
Talk is cheapShow me the code
Mongooseintroduction 
«Elegantmongodbobjectmodelingfornode.js » http://mongoosejs.com/
Mongooseconnect 
var mongoose= require('mongoose'); 
mongoose.connect('mongodb://localhost/test'); 
mongoose.connection.on('error', console.log); 
mongoose.connection.once('open', functioncallback (){ }); 
mongoose.connection.on('disconnected', functioncallback (){ });
Mongooseschema1/2 
/* Article Schema*/ 
var ArticleSchema= new Schema({ 
title: {type : String, trim : true}, 
body: {type : String, trim: true}, 
user: {type : Schema.ObjectId, ref: 'User'}, 
comments: [{ 
body: { type : String, default : '' }, 
user: { type : Schema.ObjectId, ref: 'User' }, 
createdAt: { type : Date, default : Date.now} 
}], 
createdAt: {type : Date, default : Date.now} 
}); 
/* Validations */ 
ArticleSchema.path('title').required(true, 'Article title cannot be blank'); 
ArticleSchema.path('body').required(true, 'Article body cannot be blank'); 
/* Save the Schema*/ 
mongoose.model('Article', ArticleSchema);
Mongooseschema2/2 
Othersschemafeatures: 
•Validator 
•Virtual property 
•Middleware 
•Population 
•…
Mongooseinstance & save 
/* Getthe model */ 
var Article = mongoose.model('Article'); 
/* Createa new instance */ 
var article = new Article({ 
title: 'Introduction to Mongoose', 
body : 'This is an article about Mongoose' 
}); 
/* Save the instance */ 
article.save(function(err){ 
if(err) return console.log("not saved !"); 
console.log("saved"); 
});
Mongoosequery 
var Article = mongoose.model('Article'); 
// A query 
Article 
.where('user').equals(myUserId) 
.where('tile', /mongoose/i) 
.select('titlebody createdAt') 
.sort('-createdAt') 
.limit(10) 
.exec (function (err, data){ /* do anything */ }); 
// The samequery 
Article.find({ 
user : myUserId, 
title: /mongoose/i 
}, 
'titlebody createdAt', 
{ 
sort : '-createdAt', 
limit: 10 
}, 
function (err, data){ /* do anything */ } 
);
Mongoose 
Talk is cheapShow me the code
Othersmodules 
•Web frameworksExpress, Koa, Sails, Hapi, Restify, … 
•Server toolsSocket.io, Passport, … 
•LoggersWinston, Bunyan, … 
•ToolsAsync, Q, Lodash, Moment, Cheerio, … 
•TestingNight Watch, Supertest, Mocha, Jasmine, Sinon, Chai, …
Questions?

More Related Content

What's hot

Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자NAVER D2
 
GraphQL IN Golang
GraphQL IN GolangGraphQL IN Golang
GraphQL IN GolangBo-Yi Wu
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
우아한 모노리스
우아한 모노리스우아한 모노리스
우아한 모노리스Arawn Park
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsjacekbecela
 
Kong API Gateway
Kong API Gateway Kong API Gateway
Kong API Gateway Chris Mague
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...Edureka!
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architectureBishal Khanal
 
Getting started with Next.js
Getting started with Next.jsGetting started with Next.js
Getting started with Next.jsGökhan Sarı
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideTim Burks
 
Building APIs with the OpenApi Spec
Building APIs with the OpenApi SpecBuilding APIs with the OpenApi Spec
Building APIs with the OpenApi SpecPedro J. Molina
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API TutorialSimplilearn
 
SSR with Quasar Framework - JSNation 2019
SSR with Quasar Framework - JSNation 2019SSR with Quasar Framework - JSNation 2019
SSR with Quasar Framework - JSNation 2019Razvan Stoenescu
 

What's hot (20)

Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자[131]chromium binging 기술을 node.js에 적용해보자
[131]chromium binging 기술을 node.js에 적용해보자
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Introduction to MERN
Introduction to MERNIntroduction to MERN
Introduction to MERN
 
GraphQL IN Golang
GraphQL IN GolangGraphQL IN Golang
GraphQL IN Golang
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
우아한 모노리스
우아한 모노리스우아한 모노리스
우아한 모노리스
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Kong API Gateway
Kong API Gateway Kong API Gateway
Kong API Gateway
 
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
What is Node.js | Node.js Tutorial for Beginners | Node.js Modules | Node.js ...
 
Spring boot
Spring bootSpring boot
Spring boot
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Mongodb basics and architecture
Mongodb basics and architectureMongodb basics and architecture
Mongodb basics and architecture
 
Getting started with Next.js
Getting started with Next.jsGetting started with Next.js
Getting started with Next.js
 
OpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-SideOpenAPI and gRPC Side by-Side
OpenAPI and gRPC Side by-Side
 
Building APIs with the OpenApi Spec
Building APIs with the OpenApi SpecBuilding APIs with the OpenApi Spec
Building APIs with the OpenApi Spec
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API Tutorial
 
SSR with Quasar Framework - JSNation 2019
SSR with Quasar Framework - JSNation 2019SSR with Quasar Framework - JSNation 2019
SSR with Quasar Framework - JSNation 2019
 

Viewers also liked

Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
Nodejs - Building a RESTful API
Nodejs - Building a RESTful APINodejs - Building a RESTful API
Nodejs - Building a RESTful APISang Cù
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBHengki Sihombing
 
Introduction to Google API
Introduction to Google APIIntroduction to Google API
Introduction to Google APILakhdar Meftah
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Dmytro Mindra
 
AllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCAllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCPavel Tiunov
 
Moscow js node.js enterprise development
Moscow js node.js enterprise developmentMoscow js node.js enterprise development
Moscow js node.js enterprise developmentPavel Tiunov
 
Learn Developing REST API in Node.js using LoopBack Framework
Learn Developing REST API  in Node.js using LoopBack FrameworkLearn Developing REST API  in Node.js using LoopBack Framework
Learn Developing REST API in Node.js using LoopBack FrameworkMarudi Subakti
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST APIFabien Vauchelles
 
ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS Pavel Tsukanov
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.jsTimur Shemsedinov
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsGeeksLab Odessa
 
Developing and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIDeveloping and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIAll Things Open
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsJakub Nesetril
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications7 Stages of Scaling Web Applications
7 Stages of Scaling Web ApplicationsDavid Mitzenmacher
 
Инфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.jsИнфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.jsStanislav Gumeniuk
 

Viewers also liked (20)

Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Nodejs - Building a RESTful API
Nodejs - Building a RESTful APINodejs - Building a RESTful API
Nodejs - Building a RESTful API
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDB
 
Introduction to Google API
Introduction to Google APIIntroduction to Google API
Introduction to Google API
 
Node.js (RichClient)
 Node.js (RichClient) Node.js (RichClient)
Node.js (RichClient)
 
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
Web В РЕАЛЬНОМ ВРЕМЕНИ С Node.js - AgileBaseCamp - 2012
 
AllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POCAllcountJS VTB24 loan сonveyor POC
AllcountJS VTB24 loan сonveyor POC
 
Moscow js node.js enterprise development
Moscow js node.js enterprise developmentMoscow js node.js enterprise development
Moscow js node.js enterprise development
 
Learn Developing REST API in Node.js using LoopBack Framework
Learn Developing REST API  in Node.js using LoopBack FrameworkLearn Developing REST API  in Node.js using LoopBack Framework
Learn Developing REST API in Node.js using LoopBack Framework
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS ВВЕДЕНИЕ В NODE.JS
ВВЕДЕНИЕ В NODE.JS
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.js
 
Асинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.jsАсинхронность и параллелизм в Node.js
Асинхронность и параллелизм в Node.js
 
Developing and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST APIDeveloping and Testing a MongoDB and Node.js REST API
Developing and Testing a MongoDB and Node.js REST API
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
REST API Design
REST API DesignREST API Design
REST API Design
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications7 Stages of Scaling Web Applications
7 Stages of Scaling Web Applications
 
Инфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.jsИнфраструктура распределенных приложений на Node.js
Инфраструктура распределенных приложений на Node.js
 

Similar to Introduction to REST API with Node.js

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsRichard Rodger
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverMongoDB
 

Similar to Introduction to REST API with Node.js (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Node azure
Node azureNode azure
Node azure
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Node.js on Azure
Node.js on AzureNode.js on Azure
Node.js on Azure
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Nodejs web,db,hosting
Nodejs web,db,hostingNodejs web,db,hosting
Nodejs web,db,hosting
 
ECMAScript 6 and the Node Driver
ECMAScript 6 and the Node DriverECMAScript 6 and the Node Driver
ECMAScript 6 and the Node Driver
 

More from Yoann Gotthilf

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSYoann Gotthilf
 
Most Common JavaScript Mistakes
Most Common JavaScript MistakesMost Common JavaScript Mistakes
Most Common JavaScript MistakesYoann Gotthilf
 
Introduction to the MEAN stack
Introduction to the MEAN stackIntroduction to the MEAN stack
Introduction to the MEAN stackYoann Gotthilf
 
Web development - technologies and tools
Web development - technologies and toolsWeb development - technologies and tools
Web development - technologies and toolsYoann Gotthilf
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à AndroidYoann Gotthilf
 
Développement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs WebDéveloppement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs WebYoann Gotthilf
 

More from Yoann Gotthilf (6)

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Most Common JavaScript Mistakes
Most Common JavaScript MistakesMost Common JavaScript Mistakes
Most Common JavaScript Mistakes
 
Introduction to the MEAN stack
Introduction to the MEAN stackIntroduction to the MEAN stack
Introduction to the MEAN stack
 
Web development - technologies and tools
Web development - technologies and toolsWeb development - technologies and tools
Web development - technologies and tools
 
Introduction à Android
Introduction à AndroidIntroduction à Android
Introduction à Android
 
Développement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs WebDéveloppement Web - HTML5, CSS3, APIs Web
Développement Web - HTML5, CSS3, APIs Web
 

Recently uploaded

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 

Recently uploaded (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 

Introduction to REST API with Node.js

  • 2. WhatisNode.js ? «Aplatform built onChrome's JavaScript runtime for easily building fast, scalable network applications.» http://nodejs.org/ Node.js isneithera server nora web framework
  • 3. About Node.js •Createdby Ryan Dahl in 2009 •Development and maintenance sponsored byJoyent •LicenceMIT •Last release : 0.10.31 •Based on Google V8 Engine •+99 000 packages
  • 4. Successstories Rails to Node « Servers were cut to 3 from 30 » « Running up to 20x faster in some scenarios » « Frontend and backend mobile teams could be combined […] » Java to Node « Built almost twice as fast with fewer people » « Double the requests per second » « 35% decrease in the average response time »
  • 5. Architecture •Single Threaded •Event Loop •Non-blockingI/O •Javascript(Event DrivenLanguage)
  • 6.
  • 7. Inside Node.js Standard JavaScript with •Buffer •C/C++ Addons •Child Processes •Cluster •Console •Crypto •Debugger •DNS •Domain •Events •File System •Globals •HTTP •HTTPS •Modules •Net •OS •Path •Process •Punycode •QueryStrings •Readline •REPL •Stream •String Decoder •Timers •TLS/SSL •TTY •UDP/Datagram •URL •Utilities •VM •ZLIB … but withoutDOM manipulation
  • 8. File package.json Project informations •Name •Version •Dependencies •Licence •Main file •Etc...
  • 9. NPM (NodePackagedModules) •Findpackages : https://www.npmjs.org/ •Help : npm-l •Createpackage.json: npminit •Install package : •npminstallexpress •npminstallmongosse--save •npminstall-g mocha •npm installgrunt--save-dev •Update project from package.json •npm install •npm update
  • 10. Hello Node.js console.log("Hello World !"); hello.js > nodehello.js Hello World !
  • 11. Loadmodule •Coremodule : var http = require('http'); •Project file module : var mymodule= require(‘./module’); // ./module.js or ./module/index.js var mymodule= require(‘../module.js’); var mymodule= require(‘/package.json’); •Packagedmodule (in node_modulesdirectory): var express = require(‘express’);
  • 12. Createmodule 1/2 var PI = Math.PI; exports.area= function(r) { return PI * r * r; }; var circle= require('./circle.js'); console.log('The area of a circle of radius 4 is '+ circle.area(4)); circle.js
  • 13. Createmodule 2/2 var PI = Math.PI; module.exports= function(r) { return PI * r * r; }; var circleArea= require('./circle-area.js'); console.log('The area of a circle of radius 4 is '+ circleArea(4)); circle-area.js
  • 14. Node.js Talk is cheapShow me the code
  • 15. Express introduction «Fast, unopinionated, minimalist web framework forNode.js» http://expressjs.com
  • 16. Express sample var express = require('express'); var app= express(); app.get('/', function(req, res) { res.send('Hello World!'); }); app.post('/:name', function (req, res) { res.send('Hello !'+req.param('name')); }); app.listen(3000);
  • 17. Express middleware Middleware can: •Execute any code. •Make changes to the request and the response objects. •End the request-response cycle. •Call the next middleware in the stack. var express = require('express'); var app= express(); var cookieParser= require('cookie-parser'); app.use(express.static(__dirname+ '/public')); app.use(cookieParser()); …
  • 18. Express middleware modules Module Description morgan HTTP request logger middleware for node.js express.static Serve static content from the "public" directory (js, css, html, image, video, …) body-parser Parserequestbody and populatereq.body(ie: parsejsonbody) cookie-parser Parse cookie header and populate req.cookieswith an object keyed by the cookie names cookie-session Provide "guest" sessions, meaning any visitor will have a session, authenticated or not. express-session Providegenericsession functionality within-memorystorage by default method-override Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it. csurf Node.js CSRF protection middleware. …
  • 19. Express router var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('Hello World!'); }); router.post('/:name', function(req, res) { res.send('Hello !'+req.param('name')); }); var app= express(); app.use('/api/', router);
  • 20. Express Talk is cheapShow me the code
  • 22. Mongooseconnect var mongoose= require('mongoose'); mongoose.connect('mongodb://localhost/test'); mongoose.connection.on('error', console.log); mongoose.connection.once('open', functioncallback (){ }); mongoose.connection.on('disconnected', functioncallback (){ });
  • 23. Mongooseschema1/2 /* Article Schema*/ var ArticleSchema= new Schema({ title: {type : String, trim : true}, body: {type : String, trim: true}, user: {type : Schema.ObjectId, ref: 'User'}, comments: [{ body: { type : String, default : '' }, user: { type : Schema.ObjectId, ref: 'User' }, createdAt: { type : Date, default : Date.now} }], createdAt: {type : Date, default : Date.now} }); /* Validations */ ArticleSchema.path('title').required(true, 'Article title cannot be blank'); ArticleSchema.path('body').required(true, 'Article body cannot be blank'); /* Save the Schema*/ mongoose.model('Article', ArticleSchema);
  • 24. Mongooseschema2/2 Othersschemafeatures: •Validator •Virtual property •Middleware •Population •…
  • 25. Mongooseinstance & save /* Getthe model */ var Article = mongoose.model('Article'); /* Createa new instance */ var article = new Article({ title: 'Introduction to Mongoose', body : 'This is an article about Mongoose' }); /* Save the instance */ article.save(function(err){ if(err) return console.log("not saved !"); console.log("saved"); });
  • 26. Mongoosequery var Article = mongoose.model('Article'); // A query Article .where('user').equals(myUserId) .where('tile', /mongoose/i) .select('titlebody createdAt') .sort('-createdAt') .limit(10) .exec (function (err, data){ /* do anything */ }); // The samequery Article.find({ user : myUserId, title: /mongoose/i }, 'titlebody createdAt', { sort : '-createdAt', limit: 10 }, function (err, data){ /* do anything */ } );
  • 27. Mongoose Talk is cheapShow me the code
  • 28. Othersmodules •Web frameworksExpress, Koa, Sails, Hapi, Restify, … •Server toolsSocket.io, Passport, … •LoggersWinston, Bunyan, … •ToolsAsync, Q, Lodash, Moment, Cheerio, … •TestingNight Watch, Supertest, Mocha, Jasmine, Sinon, Chai, …