SlideShare uma empresa Scribd logo
1 de 23
NodeJs
Christoffer Noring, Softhouse
History
• 2009 Created by Ryan Dahl, Joyent
• 2011 NPM, node package manager, was introducted by Isaac
Schlueter
• 2014 Timothy J Fontaine introduced as new project lead
• 2014 npmjs.org currently holds 106 287 packages, on npmjs.org
NodeJs
• Is Javascript on the backend
• Is an open source, cross-platform runtime environment for server-
side and networking applications
• Has an event-driven architecture
• Based on google v8 javascript engine
• Is awesome !
Processing model
Open file – non blocking
fs.readFile('file.csv', 'utf-8', function (err, data) {
if (!err) {
console.log('file content' + data);
} else {
console.log('error while opening file' + err);
}
}); callback
Second arg should be result
var fs = require('fs');
First arg should be error
Open file
Open file – blocking AVOID
var data;
try {
data = fs.readFileSync('foo.bar');
} catch (e) {
// handle error
}
var fs = require('fs');
blocking
Module (assembly)
( 1.1 ) Can refer to a file or a directory
( 2 ) Can be global or local in node_modules
Directory require(’moduleName’)
( 1 ) Can be in your project
// package.json
{ ”start” : ”app.js” }
var myModule = require(’./myModule’);
myModule.method();
( 1.1.1 ) Points to directory
math/index.js
var myModule = require(’myModule’)
Points default to index.js
( 1.1.2 )Points to a file
Default can be changed in package.json
project/node_modules/moduleName
var math = require(’./math’)
Example module ( is cached )
var fs = require('fs')
path = require('path')
modulePath = __dirname,
logPath = 'log',
logFile = 'logger.txt';
module.exports.log = function (message){
fs.writeFile( path.join(modulePath, logPath) + logFile,
message,
'utf-8',
function (err, data) {
if (err)
console.log("there was an error " + err);
else
console.log('This was written to file ' + data);
});
}
function privateFunction(){}; var privateVar = ”test”;
module.exports, public property / function
Private area, not seen outside module
NPM – Node package manager vs ’Nuget’
NPM
npm install <package name>
npm update
npm init
Nuget
Install-Package <package name>
Update-Package
package.json packages.config
Package.json
{
"name": "NodejsModules",
"version": "0.0.0",
"description": "NodejsModules",
"main": "app.js",
"author": {
"name": "cno",
"email": ""
},
"devDependencies": {
"express": "",
"gulp": "^3.8.10",
"gulp-mocha": "^1.1.1",
"gulp-nodemon": "^1.0.4",
"gulp-util": "^3.0.1",
"should": ""
}
dependencies : {
”express” : ””,
devDependencies, dependecies that is
needed to work on the project like
preprocessors, testing frameworks,
minification libs etc
npm install <package> --save-dev
dependencies, dependecies that is needed
for your app to run
npm install --save
~ = minor version
~1.2.3 will match all 1.2.x versions but will miss 1.3.0
^= major version
^1.2.3 will match any 1.x.x release including 1.3.0, but will
hold off on 2.0.0
API development
• Web framework
• Routing, REST
• Testing, Unit + Integration
• Error recovery, Authentication
• Backend MySql, Mongo, OR- mapper?
• Task runners for restart server +
continuous integration
EXPRESS
EXPRESS
JASMINE + FRISBY
MIDDLEWARES : PASSPORT
MONGO = >MONGOOSE OR
MYSQL/POSTGRES => SEQUELIZE
GRUNT OR GULP, pick one !
API - Minimum implementation
var express = require('express');
Var user = require(’./routes/user’)
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('env', 'development');
app.use(authMiddleware);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/users/:id', user.getone);
app.use(app.router);
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' +
app.get('port'));
});
Init express
Define routes
Start web server
Add middlewares
Routes - CRUD
app.get('/products', function (req,res) {
res.send(musicRepository.get());
});
app.get('/products/:id', function (req, res) {
res.send(musicRepository.get({
id : req.params.id }));
});
app.post('/products', function (req,res) {
musicRepository.create({
name : req.body.name,
price : req.body.price
});
});
app.put('/products', function (req, res) {
musicRepository.create({
id : req.body.id,
name : req.body.name,
price : req.body.price
});
});
POST/PUT requires bodyParser
middleware !!
request.body
request.params
Middleware
app.get('/routeThatWillIgnoreAuthentication', function (req, res) {
// do some damage
});
app.use(crappySecurityMiddleware);
function crappySecurityMiddleware(req, res, done){
if (request.headers.token && request.headers.token == "admin") {
done();
} else {
res.send('Not authenticated, please login');
}
// done is NEVER called, request dies here !
}
app.get('/willBeAuthenticated', function (req, res) {
// safer call
});
The middleware
Route NOT using middleware
1
2
1a
Call done unless you
intend to stop execution
Demo – Simple api with angular client
• LectureNode + LectureNodeClient
• Do POST call from client and show VS NodeJs Tools, debug
• Also show NPM management, install / update, see how it updates
when things are added to package json
Demo Gulp / Nodemon / Frisby
• NodeJsModules
• We want to achieve
• Start with ”gulp develop”
• Node server that relaunches on code change, automatically
• Tests to run often
• End point testing, when needed ”jasmine-node test/api”
Unit Tests Mocha, async + sync
describe('call to long running function', function () {
it('should produce data', function (done) {
var req = {
send : function (data) {
expect(data.length).toBe(3);
done();
}
};
var _route.getPerson(req,res);
})
})
done() Signals to test framework that test is done
Request object calls send() when async call is done
Mocking
What if you have a method that calls IO/ Database, how to test?
function aMethod(someParam){
if (someParam) {
var content = fs.openFileSync(’file.txt’,’utf-8’);
console.log(content);
} else {
// do something
}
}
Hard to test right?
Use mockery
var mockery = require(‘mockery‘);
var fsMock = { openFileSync : function(){ console.log(“mocked”); } }
mockery.registerMock(‘fs’,fsMock);
Or if its more complicated
mockery.registerSubstitute(‘fs’,’fs-mockedModule’); Replace one module for another
Tests - frisby
frisby.create('GET JSON data from /products/1')
.get('http://localhost:8000/products/1')
.expectStatus(200)
.afterJSON(function (body) {
expect(body.id).toMatch(2)
})
.toss();
frisby.create('GET JSON data from /products')
.get('http://localhost:8000/products')
.expectStatus(200)
.afterJSON(function (body) {
expect(body.length).toMatch(2);
})
.toss();
afterJson, investigates the data
coming back from api call
Callback hell , the problem
The problem
You want to do several tasks when creating a user
1) Validate user does not exist before
2) Validate input data is valid
3) Create person in db
4) Write to event log ’person created’
5) Respond with created user
Some operations are async and therefore we get a
callback tree
repo
.getUser(req.body.name)
.success(function (data) {
if (data == null) {
repo
.createPerson(req.body)
.success(function (person) {
repo
.createEvent(’person created’)
.success(function () {
res.send(data);
});
});
}
}); Sending data to user
Introducing the event emitter
emitter.on(’eventName', callback);
var events = require(’events’);
var EventEmitter = = new events.EventEmitter();
function doStuff(){
emitter.emit(’eventName’,<optional data>);
}
Trigger the event
setup event and act accordingly
function callback(<optional event data>){
}
Callback hell – a solution
function CreatePerson(){
var me = this;
function _validateUserDidNotExistBefore(){
me.emit('ev_userDidNotExistBefore');
}
this.on('ev_userDidNotExistBefore', _validateInputData);
this.on('ev_inputValidated', _createPerson);
this.on('ev_personCreated', _createLogEventEntry);
this.on('ev_error', function () {
res.send('error');
})
this.create = function (){
_validateUserDidNotExistBefore();
}
}
util.inherits(CreatePerson, EventEmitter);
Public function
Chain of events,” if x then y”
Event trigger
CreatePerson inherits from EventEmitter
Questions?
• www.nodejs.org
• Pluralsight, hadi hariri
• www.npmjs.org

Mais conteúdo relacionado

Mais procurados

Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기JeongHun Byeon
 
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero ClicksHow to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero ClicksCarlos Sanchez
 
Cutting Back Processing Time
Cutting Back Processing TimeCutting Back Processing Time
Cutting Back Processing TimeHenrique Moody
 
Hacking Mac OSX Cocoa API from Perl
Hacking Mac OSX Cocoa API from PerlHacking Mac OSX Cocoa API from Perl
Hacking Mac OSX Cocoa API from Perltypester
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensNETWAYS
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Using Puppet to Create a Dynamic Network - PuppetConf 2013
Using Puppet to Create a Dynamic Network - PuppetConf 2013Using Puppet to Create a Dynamic Network - PuppetConf 2013
Using Puppet to Create a Dynamic Network - PuppetConf 2013Puppet
 
Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)julien pauli
 
Puppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the ForgePuppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the ForgePuppet
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Ilya Haykinson
 
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorStanislav Tiurikov
 
Legacy applications - 4Developes konferencja, Piotr Pasich
Legacy applications  - 4Developes konferencja, Piotr PasichLegacy applications  - 4Developes konferencja, Piotr Pasich
Legacy applications - 4Developes konferencja, Piotr PasichPiotr Pasich
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212Mahmoud Samir Fayed
 
Python mongo db-training-europython-2011
Python mongo db-training-europython-2011Python mongo db-training-europython-2011
Python mongo db-training-europython-2011Andreas Jung
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsShinpei Hayashi
 

Mais procurados (20)

Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기Node.js API 서버 성능 개선기
Node.js API 서버 성능 개선기
 
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero ClicksHow to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
 
Cutting Back Processing Time
Cutting Back Processing TimeCutting Back Processing Time
Cutting Back Processing Time
 
What is nodejs
What is nodejsWhat is nodejs
What is nodejs
 
Hacking Mac OSX Cocoa API from Perl
Hacking Mac OSX Cocoa API from PerlHacking Mac OSX Cocoa API from Perl
Hacking Mac OSX Cocoa API from Perl
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
Zabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet MensZabbix LLD from a C Module by Jan-Piet Mens
Zabbix LLD from a C Module by Jan-Piet Mens
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Using Puppet to Create a Dynamic Network - PuppetConf 2013
Using Puppet to Create a Dynamic Network - PuppetConf 2013Using Puppet to Create a Dynamic Network - PuppetConf 2013
Using Puppet to Create a Dynamic Network - PuppetConf 2013
 
Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)
 
Puppet modules for Fun and Profit
Puppet modules for Fun and ProfitPuppet modules for Fun and Profit
Puppet modules for Fun and Profit
 
Puppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the ForgePuppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the Forge
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4
 
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with InfrastructorGr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
Gr8conf EU 2018 - Bring you infrastructure under control with Infrastructor
 
Legacy applications - 4Developes konferencja, Piotr Pasich
Legacy applications  - 4Developes konferencja, Piotr PasichLegacy applications  - 4Developes konferencja, Piotr Pasich
Legacy applications - 4Developes konferencja, Piotr Pasich
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212
 
Python mongo db-training-europython-2011
Python mongo db-training-europython-2011Python mongo db-training-europython-2011
Python mongo db-training-europython-2011
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring Effects
 

Semelhante a NodeJs

Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 
Node Powered Mobile
Node Powered MobileNode Powered Mobile
Node Powered MobileTim Caswell
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascriptEldar Djafarov
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLaurence Svekis ✔
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
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
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.jsdavidchubbs
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensionserwanl
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 

Semelhante a NodeJs (20)

Node intro
Node introNode intro
Node intro
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 
Node Powered Mobile
Node Powered MobileNode Powered Mobile
Node Powered Mobile
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
NodeJS
NodeJSNodeJS
NodeJS
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
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
 
Unit testing
Unit testingUnit testing
Unit testing
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
node.js dao
node.js daonode.js dao
node.js dao
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
NodeJS
NodeJSNodeJS
NodeJS
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 

Último

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

NodeJs

  • 2. History • 2009 Created by Ryan Dahl, Joyent • 2011 NPM, node package manager, was introducted by Isaac Schlueter • 2014 Timothy J Fontaine introduced as new project lead • 2014 npmjs.org currently holds 106 287 packages, on npmjs.org
  • 3. NodeJs • Is Javascript on the backend • Is an open source, cross-platform runtime environment for server- side and networking applications • Has an event-driven architecture • Based on google v8 javascript engine • Is awesome !
  • 5. Open file – non blocking fs.readFile('file.csv', 'utf-8', function (err, data) { if (!err) { console.log('file content' + data); } else { console.log('error while opening file' + err); } }); callback Second arg should be result var fs = require('fs'); First arg should be error Open file
  • 6. Open file – blocking AVOID var data; try { data = fs.readFileSync('foo.bar'); } catch (e) { // handle error } var fs = require('fs'); blocking
  • 7. Module (assembly) ( 1.1 ) Can refer to a file or a directory ( 2 ) Can be global or local in node_modules Directory require(’moduleName’) ( 1 ) Can be in your project // package.json { ”start” : ”app.js” } var myModule = require(’./myModule’); myModule.method(); ( 1.1.1 ) Points to directory math/index.js var myModule = require(’myModule’) Points default to index.js ( 1.1.2 )Points to a file Default can be changed in package.json project/node_modules/moduleName var math = require(’./math’)
  • 8. Example module ( is cached ) var fs = require('fs') path = require('path') modulePath = __dirname, logPath = 'log', logFile = 'logger.txt'; module.exports.log = function (message){ fs.writeFile( path.join(modulePath, logPath) + logFile, message, 'utf-8', function (err, data) { if (err) console.log("there was an error " + err); else console.log('This was written to file ' + data); }); } function privateFunction(){}; var privateVar = ”test”; module.exports, public property / function Private area, not seen outside module
  • 9. NPM – Node package manager vs ’Nuget’ NPM npm install <package name> npm update npm init Nuget Install-Package <package name> Update-Package package.json packages.config
  • 10. Package.json { "name": "NodejsModules", "version": "0.0.0", "description": "NodejsModules", "main": "app.js", "author": { "name": "cno", "email": "" }, "devDependencies": { "express": "", "gulp": "^3.8.10", "gulp-mocha": "^1.1.1", "gulp-nodemon": "^1.0.4", "gulp-util": "^3.0.1", "should": "" } dependencies : { ”express” : ””, devDependencies, dependecies that is needed to work on the project like preprocessors, testing frameworks, minification libs etc npm install <package> --save-dev dependencies, dependecies that is needed for your app to run npm install --save ~ = minor version ~1.2.3 will match all 1.2.x versions but will miss 1.3.0 ^= major version ^1.2.3 will match any 1.x.x release including 1.3.0, but will hold off on 2.0.0
  • 11. API development • Web framework • Routing, REST • Testing, Unit + Integration • Error recovery, Authentication • Backend MySql, Mongo, OR- mapper? • Task runners for restart server + continuous integration EXPRESS EXPRESS JASMINE + FRISBY MIDDLEWARES : PASSPORT MONGO = >MONGOOSE OR MYSQL/POSTGRES => SEQUELIZE GRUNT OR GULP, pick one !
  • 12. API - Minimum implementation var express = require('express'); Var user = require(’./routes/user’) var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('env', 'development'); app.use(authMiddleware); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); app.get('/users/:id', user.getone); app.use(app.router); http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); Init express Define routes Start web server Add middlewares
  • 13. Routes - CRUD app.get('/products', function (req,res) { res.send(musicRepository.get()); }); app.get('/products/:id', function (req, res) { res.send(musicRepository.get({ id : req.params.id })); }); app.post('/products', function (req,res) { musicRepository.create({ name : req.body.name, price : req.body.price }); }); app.put('/products', function (req, res) { musicRepository.create({ id : req.body.id, name : req.body.name, price : req.body.price }); }); POST/PUT requires bodyParser middleware !! request.body request.params
  • 14. Middleware app.get('/routeThatWillIgnoreAuthentication', function (req, res) { // do some damage }); app.use(crappySecurityMiddleware); function crappySecurityMiddleware(req, res, done){ if (request.headers.token && request.headers.token == "admin") { done(); } else { res.send('Not authenticated, please login'); } // done is NEVER called, request dies here ! } app.get('/willBeAuthenticated', function (req, res) { // safer call }); The middleware Route NOT using middleware 1 2 1a Call done unless you intend to stop execution
  • 15. Demo – Simple api with angular client • LectureNode + LectureNodeClient • Do POST call from client and show VS NodeJs Tools, debug • Also show NPM management, install / update, see how it updates when things are added to package json
  • 16. Demo Gulp / Nodemon / Frisby • NodeJsModules • We want to achieve • Start with ”gulp develop” • Node server that relaunches on code change, automatically • Tests to run often • End point testing, when needed ”jasmine-node test/api”
  • 17. Unit Tests Mocha, async + sync describe('call to long running function', function () { it('should produce data', function (done) { var req = { send : function (data) { expect(data.length).toBe(3); done(); } }; var _route.getPerson(req,res); }) }) done() Signals to test framework that test is done Request object calls send() when async call is done
  • 18. Mocking What if you have a method that calls IO/ Database, how to test? function aMethod(someParam){ if (someParam) { var content = fs.openFileSync(’file.txt’,’utf-8’); console.log(content); } else { // do something } } Hard to test right? Use mockery var mockery = require(‘mockery‘); var fsMock = { openFileSync : function(){ console.log(“mocked”); } } mockery.registerMock(‘fs’,fsMock); Or if its more complicated mockery.registerSubstitute(‘fs’,’fs-mockedModule’); Replace one module for another
  • 19. Tests - frisby frisby.create('GET JSON data from /products/1') .get('http://localhost:8000/products/1') .expectStatus(200) .afterJSON(function (body) { expect(body.id).toMatch(2) }) .toss(); frisby.create('GET JSON data from /products') .get('http://localhost:8000/products') .expectStatus(200) .afterJSON(function (body) { expect(body.length).toMatch(2); }) .toss(); afterJson, investigates the data coming back from api call
  • 20. Callback hell , the problem The problem You want to do several tasks when creating a user 1) Validate user does not exist before 2) Validate input data is valid 3) Create person in db 4) Write to event log ’person created’ 5) Respond with created user Some operations are async and therefore we get a callback tree repo .getUser(req.body.name) .success(function (data) { if (data == null) { repo .createPerson(req.body) .success(function (person) { repo .createEvent(’person created’) .success(function () { res.send(data); }); }); } }); Sending data to user
  • 21. Introducing the event emitter emitter.on(’eventName', callback); var events = require(’events’); var EventEmitter = = new events.EventEmitter(); function doStuff(){ emitter.emit(’eventName’,<optional data>); } Trigger the event setup event and act accordingly function callback(<optional event data>){ }
  • 22. Callback hell – a solution function CreatePerson(){ var me = this; function _validateUserDidNotExistBefore(){ me.emit('ev_userDidNotExistBefore'); } this.on('ev_userDidNotExistBefore', _validateInputData); this.on('ev_inputValidated', _createPerson); this.on('ev_personCreated', _createLogEventEntry); this.on('ev_error', function () { res.send('error'); }) this.create = function (){ _validateUserDidNotExistBefore(); } } util.inherits(CreatePerson, EventEmitter); Public function Chain of events,” if x then y” Event trigger CreatePerson inherits from EventEmitter
  • 23. Questions? • www.nodejs.org • Pluralsight, hadi hariri • www.npmjs.org