SlideShare uma empresa Scribd logo
1 de 99
NodeJS
JsFoo!
Wifi Details
• SSID:
• HasGeek
• HasGeek-Wifi
• Password:
• geeksrus
About me
• Currently Head of Engineering @
Hopscotch
• Xoogler
• Entrepreneur
• Corporate Trainer
• Author
• AngularJS & AngularJS Up &
Running for O’Reilly
• MBA
• Geek!
Agenda
• 1 day
• Smaller, multiple sessions
• Code Along
• As fast or slow as needed
• Questions, interrupt any time
Agenda - Continued
• Introduction
• JS on the Server
• NodeJS Concepts
• Starting NodeJS
• NPM & Requires
Agenda - Continued
• Working with Node
packages
• Async
• Express
• Routes & Config
• NPM & Requires
Agenda - Continued
• Middleware
• Working with MongoDB
• Build & Deploy
• Sockets?
Requirements
• NodeJS (http://nodejs.org)
• A good IDE (Recommend Webstorm)
Getting the Code Base
http://is.gd/nodejsfoo
The Basics
Agenda
• Introduction
• JS On the Server & Evolution
• NodeJS - How it works
• Basic Concepts and Terminologies
• Hello NodeJS
• NPM & Requires
Evolution of Server side
programming
• CGI / Perl
• Java / ASP
• Ruby, PHP, Python
• Move towards reusable, maintainable, fast
• MVC, Components
Why JS on the server side
sounds crazy!
Single Threaded Slow, Clunky
No OO! No Type Safety
What changed?
libev V8
• Event Engine
• Non blocking
• Core underlying
NodeJS
• JS Engine
• From Chromium
• Super Fast!
So what is NodeJS?
Not a programming language, but not simply
a framework either. For servers as well as for
scripts!
Core NodeJS Concepts
Event Loop! Non blocking
Single
Threaded
Callbacks
FTW!
A Thinking Paradigm Shift
teams = teamsDb.getTeams();
for (var i = 0; i < teams.size(); i++) {
team = teams.get(i);
team.setExtraInfo(
teamsDb.getTeamExtraInfo(team.getId());
}
return teams;
How would we speed it up?
• Threading?
• Parallelization?
• Identifying the bottlenecks
What if?
• teamDb.getTeams was asynchronous
• teamDb.getTeams(function(teams) {});
• Same for teamDb.getTeamExtraInfo
• teamDb.getTeamExtraInf(function(team) {});
A Thinking Paradigm Shift
teamsDb.getTeams(function(teams) {
for (var i = 0; i < teams.size(); i++) {
team = teams.get(i);
teamsDb.getTeamExtraInfo(team.getId(),
function(teamExtra) {
team.setTeamExtraInfo(teamExtra);
});
}
// return teams; ?????
});
Now what about NodeJS?
• Callback oriented
• Forced to think about what to do about
callback
• Forces you to think if you need to wait for it
or continue
• Parallel friendly approach —> Default
Installing Node
• Directly, from nodejs.org
• Using nvm – Node Version Manager
– Easier to update, and switch versions
When to use NodeJS?
• IO intensive
– File, DB
• Web Servers
– More concurrent connections, cheaper!
• Scripts / Tools
– Command line toolbelt
When to avoid NodeJS
• CPU intensive
• Long running synchronous tasks
• Mathematical Operations – Floating
Numbers
So how do we start?
• Hello world example
Code-along starts now
Github Repo
http://is.gd/nodejsfoo
Code Along – Initial Setup
Checkout:
git clone https://github.com/Fundoo-
Solutions/nodejsfoo.git
cd nodejsfoo
Code Along
Step 1 - Simple Hello World
Step 2 - Handling Arguments & Inputs
Step 3 - Using Inbuilt Libraries
Step 4 - Event Handling & Callbacks
Step 5 - Sharing Logic Between Files
Step 1 – Simple Hello World
• console.log
• With multiple arguments
• Running it
• node <filename>
Step 2 - Handling Arguments and
Inputs
• process.argv
• First two arguments
• node
• filename
• Then
• arguments in order from command line
• array of strings
Step 3 – Inbuilt Libraries - fs
• Pull in libraries using
• require()
• require(‘fs’);
• fs.readFileSync(filename, encoding);
• fs.readFile is better!
• Read as pure string!
Step 4 – Event handling and
callbacks
• var stream = fs.createReadStream(filename)
• stream.on(‘data’, function(data) {})
• stream.on(‘end’, function() {})
• stream.on(‘error’, function(err) {})
Step 5 – Sharing logic
between files
• module.exports = {getStocks:}
• require
• Starting with ./ for relative!
• fs.readFile
• Pass callback for async activity finish!
Core Inbuilt Libraries
• fs
• http
• url
What about?
• Sockets
• Web Servers
• Configuration
• Database / ORM
• Something else?
Introducing NPM
• Node Package Manager
• Equivalent to Maven in Java
• Comprises
• package.json
• Global + local packages
How many NPM Packages are out
there?
1,80,000+
How does a package.json
look like?
{
"name": ”DEMO App",
"description": "DEMO App for Workshop",
"version": "0.0.1",
"private": true,
"engines": {
"node": "0.10.x",
"npm": "1.3.x"
},
"dependencies": {
"express" : "4.1.1",
"body-parser" : "1.0.2",
…
}
}
Installing a package
npm install package-name
Installing a global package
npm install –g package-name
Installing all packages for a
project
npm install
(assuming a package.json file)
Installing a package & saving it to
package.json
npm install --save package-name
Start to server
Agenda
• Working with Node packages
• NPM & Requires
• Async
• Express
• Routes & Config
How does a package.json
look like?
{
"name": ”DEMO App",
"description": "DEMO App for Workshop",
"version": "0.0.1",
"private": true,
"engines": {
"node": "0.10.x",
"npm": "1.3.x"
},
"dependencies": {
"express" : "4.1.1",
"body-parser" : "1.0.2",
…
}
}
Package.json syntax &
versioning
• MAJOR.MINOR.PATCH
• “primus”: “1.2.3”
• Specific
• *, x - wildcard support
• “async”: “*”
• ~ - Atleast, in this minor release
• “async”: “~0.8.1”
• >= 0.8.1
• < 0.9.0
Package.json syntax &
versioning
• ^ - More relaxed versioning
• “async” : “^0.8.0”
• >= 0.8.0
• < 1.0.0
• Recommendation:
• Use ^, the default
Package.json – Dependencies vs
Dev Dependencies
• dependencies
• Always needed
• Production!
• devDependencies
• Same syntax
• Installed unless NODE_ENV=production
npm Scripts
• scripts: {}
• test, start, whateveryouwant
• Shell commands
• echo “Deploying…”
• node index.js
• Shortcuts
• Run using npm run
async
• For easier dealing with multiple asynchronous
calls
• Point in case, async.parallel
• An array or object with functions
• Each function takes a callback as parameter
• Once all functions are done, proceeds to a
final block
Code Along
Step 6 - Init your package.son
Step 7 - Install and use async
Step 6 - Initing Package.son
npm init
(And answer all the questions)
Step 7 – Use async
• npm install --save async
• Understanding async parallel
• read files in async.parallel
• Do composite work in final callback
Express
• A web server framework for NodeJS
• The de-facto web server for most NodeJS apps
• The E in MEAN stack
• Configurable, extensible
• Middleware based plugins
Express Components
Routing Handlers
Middlewares
Templating /
Rendering
Creating an Express NodeJS
App
If from scratch
(npm install –g express)
express init
AngularJS + Express?
Use the angular-fullstack Yeoman generator
Express Router
• app.
• get
• post
• put
• delete
• patch
• and more…
Express Handlers
• function(req, res) {}
• function(req, res, next) {}
• What’s next?
• function(err, req, res, next) {}
Code Along
Step 8 - Start an express app
Step 9 - Create routes and handlers
Step 10 - Handling post requests
Step 8 – Start Express App
• npm install --save express
• var express = require(‘express’);
• var app = express();
• app.listen(port, function() {});
• app.get(‘/’, function(req, res) {});
Step 9 – Create routes and
handlers
• Move logic into get(‘/)
• res.send(json);
• or res.json(json);
• Parametrized get (‘/:id’)
• Access using req.params.id
• res.status(400) if not found, along with json payload
Step 10 – Handling post
routes
• npm install --save body-parser
• app.use(bodyParser.urlencoded({extended: true}));
• app.use(bodyParser.json());
• app.use(express.static(__dirname + '/public'));
• app.post('/register', function(req, res) {});
• req.body
• Watch out for ordering of routes and collisions!
Express Configuration
• Environment based
• Global + Environment Specific
• Express settings & Middlewares
Express Routers - Advanced
• var router = express.Router(optionsObj)
• caseSensitive
• strict
• /foo and /foo/ same by default
• router.use
• router.get / post / …
• app.use(‘/api/test’, router);
Nesting Routers
• var router1 = express.Router(optionsObj)
• var router2 = express.Router(optionsObj)
• router1.get(‘/user’, …)
• router1.post(‘/user’/, …)
• router2.use(‘/api’, router1);
• /api/user routes will be created
Multiple Environments
• Common configuration
• Environment specific
• development
• production
• Environment variables + configured constants
• Secure Info -> Environment Variables
• Otherwise, in code, checked in
What can you configure?
• DB urls
• application urls
• social media integration
• Anything and everything
Middlewares
• Extension, without inheritance
• Layered approach
• Decide if ok to proceed
• or skip to error
Code Along
Step 11 - Use nested routers
Step 12 - Understanding middlewares
Step 11 – Use nested routers
• Create stocks.routes.js, user.routes.js
• var express = require(‘express’);
• var router = express.Router()
• router.get(‘/’, function(req, res) {});
• module.exports = function(app) {
app.use(‘/path’, router);
}
Step 12 – Understanding
Middleware
• function(req, res) {}
• function(req, res, next) {}
• What’s next?
• Common Error Handling
• function(err, req, res, next) {}
• Ordering is important!
Configuration in NodeJS
• JSON Config files
• One per environment, one global
• Set environment variable before running app
• Read from process.env
• Load file
• export
A note about authentication
• Don’t reinvent the wheel
• Connect -> Middleware for common use cases
• Passport -> Out of the box authentication framework
for NodeJS & Express
• Support for DB backed
• FB, Google, Twitter OAuth
• And more!
Agenda
• Working with MongoDB & SQL
• Build & Deploy
• Best Practices
• Further Readings
Using Databases
• MongoDB -> JSON object store
• SQL -> not natively JSON
• Use ORMs when possible
When does NoSQL make
sense?
• Non relational data
• Transactions not required
• Atomic, single document commits
• Fast!!!
• Document store
Mongoose for MongoDB
• ORM layer for MongoDB
• Define
• Schemas
• Validations
• Pre/post save hooks
• Querying capabilities
Code Along
Step 13 - Switch to MongoDB
Step 13 – Using MongoDB
• Create Schemas & Models (stocks.model.js)
• var StockSchema = new mongoose.Schema({// def //})
• var StockModel = mongoose.model(‘Stock’, StockSchema);
• Export it
• Controller
• Require model, and use find and findOne
• Same callback structure
• index.js
• mongoose.connect('mongodb://jsfoo:jsfoo2015@ds049997.mongolab.com:4999
7/nodejsfoo')
SQL in NodeJS
• Sequelize
• BookshelfJS
• Both offer no MSSQL support
• msnodesql
• node-odbc
• mssql-orm
Debugging NodeJS
• WebStorm
• Debug mode
• Create run configurations
• Start debugging
• Add breakpoints
Debugging NodeJS
• http://nodejs.org/api/debugger.htm
• Manually
– Add debugger statement to code
– Run using node debug index.js
– c, n, s, o
• continue, next, step in, out
– repl
• evaluate commands on the fly
Build & Deploy
• Grunt / Gulp
• Run the tests before deploying
• No node_modules
• Ship entire folder
• Run npm install at installation location
• Point at main entry point
• Environment driven!
Structuring your Express Codebase
• Folders
– api
• route level
• controller, spec, model, routes
– auth
• routes
• strategies
• common
– config
• passport
• express
• environment based
– views
– components
Keeping the server running
• NodeJS crashes and stops
• Use forever
• Or an external process to keep restarting it
Best Practices
• Structure, modules
• Parallelize when possible
• Think about it at every step
• Use libraries like async, underscore
• Search for existing npm packages
• Use Middlewares
• over calling functions in controllers and handlers
• ^ or ~ versions in package.json
• Otherwise keep it up to date on a monthly basis
Best Practices
• Follow the callback pattern
• Don’t break the err, data structure in your code
• Watch out for async behavior within loops
• Closure, but extract functions instead of inline
• Use javascriptlint
• or something similar
• Use forever, nodemon, or something similar
• To ensure your app doesn’t crash and burn
• Can use it locally as well Restart on file change
Other Useful Libraries
• async
• underscore
• RabbitMQ – for Queues and RPC Servers
• SocketIO / SockJS
Code Along
Socket based NodeJS App
AngularJS + NodeJS Chat App
• Setup Socket Listeners and Posters on NodeJS
• Using SocketIO
• Client side already setup
• io.on(‘connection’, function(socket) {});
• socket.on(‘event’, function(data) {});
• io.emit(‘event’, data)
• broadcast to all!
Further Reading
• Clusters
• RabbitMQ
• SocketIO
• vasync
• More observable, async
• restify
• Pure RESTful services, not web apps
Cluster Example
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
}
Cluster Example - continued
else {
// Workers can share any TCP connection
// In this case its a HTTP server
http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello worldn");
}).listen(8000);
}
How it works
• Child processes spawned using fork
• Communicate with parent using IPC
• Pass server handles back and forth
• Server.listen in child
• Serializes arguments
• Passes to master process
• Handle to server created or passed to child
• OS responsible for load balancing across processes
sharing same resource
In summary
Thank you
• Contact
• shyam@hopscotch.in
• @omniscient1
• Come join me at Hopscotch if you want to work
on exciting stuff with a great company!
• WE ARE HIRING!
Hopscotch in Brief
• Customer focused, Content oriented, discovery oriented shopping experience for moms!
• Not an Amazon/Flipkart model
• Vertical focused
• Great leadership team
• Harvard, INSEAD, Amazon, Google…
• Amazing investors
• Eduardo (FB Co-founder), Velos Partners, and more!
• Customer focused, smart and rapid growth
• 20-30% month on month!
• Scrappy, hacker oriented culture
• Come be a part of something awesome!

Mais conteúdo relacionado

Último

🐬 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
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Último (20)

🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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...
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Destaque

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 

Destaque (20)

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 

NodeJS @ JSFoo 2015

  • 2. Wifi Details • SSID: • HasGeek • HasGeek-Wifi • Password: • geeksrus
  • 3. About me • Currently Head of Engineering @ Hopscotch • Xoogler • Entrepreneur • Corporate Trainer • Author • AngularJS & AngularJS Up & Running for O’Reilly • MBA • Geek!
  • 4. Agenda • 1 day • Smaller, multiple sessions • Code Along • As fast or slow as needed • Questions, interrupt any time
  • 5. Agenda - Continued • Introduction • JS on the Server • NodeJS Concepts • Starting NodeJS • NPM & Requires
  • 6. Agenda - Continued • Working with Node packages • Async • Express • Routes & Config • NPM & Requires
  • 7. Agenda - Continued • Middleware • Working with MongoDB • Build & Deploy • Sockets?
  • 8. Requirements • NodeJS (http://nodejs.org) • A good IDE (Recommend Webstorm)
  • 9. Getting the Code Base http://is.gd/nodejsfoo
  • 11. Agenda • Introduction • JS On the Server & Evolution • NodeJS - How it works • Basic Concepts and Terminologies • Hello NodeJS • NPM & Requires
  • 12. Evolution of Server side programming • CGI / Perl • Java / ASP • Ruby, PHP, Python • Move towards reusable, maintainable, fast • MVC, Components
  • 13. Why JS on the server side sounds crazy! Single Threaded Slow, Clunky No OO! No Type Safety
  • 14. What changed? libev V8 • Event Engine • Non blocking • Core underlying NodeJS • JS Engine • From Chromium • Super Fast!
  • 15. So what is NodeJS? Not a programming language, but not simply a framework either. For servers as well as for scripts!
  • 16. Core NodeJS Concepts Event Loop! Non blocking Single Threaded Callbacks FTW!
  • 17. A Thinking Paradigm Shift teams = teamsDb.getTeams(); for (var i = 0; i < teams.size(); i++) { team = teams.get(i); team.setExtraInfo( teamsDb.getTeamExtraInfo(team.getId()); } return teams;
  • 18. How would we speed it up? • Threading? • Parallelization? • Identifying the bottlenecks
  • 19. What if? • teamDb.getTeams was asynchronous • teamDb.getTeams(function(teams) {}); • Same for teamDb.getTeamExtraInfo • teamDb.getTeamExtraInf(function(team) {});
  • 20. A Thinking Paradigm Shift teamsDb.getTeams(function(teams) { for (var i = 0; i < teams.size(); i++) { team = teams.get(i); teamsDb.getTeamExtraInfo(team.getId(), function(teamExtra) { team.setTeamExtraInfo(teamExtra); }); } // return teams; ????? });
  • 21. Now what about NodeJS? • Callback oriented • Forced to think about what to do about callback • Forces you to think if you need to wait for it or continue • Parallel friendly approach —> Default
  • 22. Installing Node • Directly, from nodejs.org • Using nvm – Node Version Manager – Easier to update, and switch versions
  • 23. When to use NodeJS? • IO intensive – File, DB • Web Servers – More concurrent connections, cheaper! • Scripts / Tools – Command line toolbelt
  • 24. When to avoid NodeJS • CPU intensive • Long running synchronous tasks • Mathematical Operations – Floating Numbers
  • 25. So how do we start? • Hello world example
  • 28. Code Along – Initial Setup Checkout: git clone https://github.com/Fundoo- Solutions/nodejsfoo.git cd nodejsfoo
  • 29. Code Along Step 1 - Simple Hello World Step 2 - Handling Arguments & Inputs Step 3 - Using Inbuilt Libraries Step 4 - Event Handling & Callbacks Step 5 - Sharing Logic Between Files
  • 30. Step 1 – Simple Hello World • console.log • With multiple arguments • Running it • node <filename>
  • 31. Step 2 - Handling Arguments and Inputs • process.argv • First two arguments • node • filename • Then • arguments in order from command line • array of strings
  • 32. Step 3 – Inbuilt Libraries - fs • Pull in libraries using • require() • require(‘fs’); • fs.readFileSync(filename, encoding); • fs.readFile is better! • Read as pure string!
  • 33. Step 4 – Event handling and callbacks • var stream = fs.createReadStream(filename) • stream.on(‘data’, function(data) {}) • stream.on(‘end’, function() {}) • stream.on(‘error’, function(err) {})
  • 34. Step 5 – Sharing logic between files • module.exports = {getStocks:} • require • Starting with ./ for relative! • fs.readFile • Pass callback for async activity finish!
  • 35. Core Inbuilt Libraries • fs • http • url
  • 36. What about? • Sockets • Web Servers • Configuration • Database / ORM • Something else?
  • 37. Introducing NPM • Node Package Manager • Equivalent to Maven in Java • Comprises • package.json • Global + local packages
  • 38. How many NPM Packages are out there? 1,80,000+
  • 39. How does a package.json look like? { "name": ”DEMO App", "description": "DEMO App for Workshop", "version": "0.0.1", "private": true, "engines": { "node": "0.10.x", "npm": "1.3.x" }, "dependencies": { "express" : "4.1.1", "body-parser" : "1.0.2", … } }
  • 40. Installing a package npm install package-name
  • 41. Installing a global package npm install –g package-name
  • 42. Installing all packages for a project npm install (assuming a package.json file)
  • 43. Installing a package & saving it to package.json npm install --save package-name
  • 45. Agenda • Working with Node packages • NPM & Requires • Async • Express • Routes & Config
  • 46. How does a package.json look like? { "name": ”DEMO App", "description": "DEMO App for Workshop", "version": "0.0.1", "private": true, "engines": { "node": "0.10.x", "npm": "1.3.x" }, "dependencies": { "express" : "4.1.1", "body-parser" : "1.0.2", … } }
  • 47. Package.json syntax & versioning • MAJOR.MINOR.PATCH • “primus”: “1.2.3” • Specific • *, x - wildcard support • “async”: “*” • ~ - Atleast, in this minor release • “async”: “~0.8.1” • >= 0.8.1 • < 0.9.0
  • 48. Package.json syntax & versioning • ^ - More relaxed versioning • “async” : “^0.8.0” • >= 0.8.0 • < 1.0.0 • Recommendation: • Use ^, the default
  • 49. Package.json – Dependencies vs Dev Dependencies • dependencies • Always needed • Production! • devDependencies • Same syntax • Installed unless NODE_ENV=production
  • 50. npm Scripts • scripts: {} • test, start, whateveryouwant • Shell commands • echo “Deploying…” • node index.js • Shortcuts • Run using npm run
  • 51. async • For easier dealing with multiple asynchronous calls • Point in case, async.parallel • An array or object with functions • Each function takes a callback as parameter • Once all functions are done, proceeds to a final block
  • 52. Code Along Step 6 - Init your package.son Step 7 - Install and use async
  • 53. Step 6 - Initing Package.son npm init (And answer all the questions)
  • 54. Step 7 – Use async • npm install --save async • Understanding async parallel • read files in async.parallel • Do composite work in final callback
  • 55. Express • A web server framework for NodeJS • The de-facto web server for most NodeJS apps • The E in MEAN stack • Configurable, extensible • Middleware based plugins
  • 57. Creating an Express NodeJS App If from scratch (npm install –g express) express init
  • 58. AngularJS + Express? Use the angular-fullstack Yeoman generator
  • 59. Express Router • app. • get • post • put • delete • patch • and more…
  • 60. Express Handlers • function(req, res) {} • function(req, res, next) {} • What’s next? • function(err, req, res, next) {}
  • 61. Code Along Step 8 - Start an express app Step 9 - Create routes and handlers Step 10 - Handling post requests
  • 62. Step 8 – Start Express App • npm install --save express • var express = require(‘express’); • var app = express(); • app.listen(port, function() {}); • app.get(‘/’, function(req, res) {});
  • 63. Step 9 – Create routes and handlers • Move logic into get(‘/) • res.send(json); • or res.json(json); • Parametrized get (‘/:id’) • Access using req.params.id • res.status(400) if not found, along with json payload
  • 64. Step 10 – Handling post routes • npm install --save body-parser • app.use(bodyParser.urlencoded({extended: true})); • app.use(bodyParser.json()); • app.use(express.static(__dirname + '/public')); • app.post('/register', function(req, res) {}); • req.body • Watch out for ordering of routes and collisions!
  • 65. Express Configuration • Environment based • Global + Environment Specific • Express settings & Middlewares
  • 66. Express Routers - Advanced • var router = express.Router(optionsObj) • caseSensitive • strict • /foo and /foo/ same by default • router.use • router.get / post / … • app.use(‘/api/test’, router);
  • 67. Nesting Routers • var router1 = express.Router(optionsObj) • var router2 = express.Router(optionsObj) • router1.get(‘/user’, …) • router1.post(‘/user’/, …) • router2.use(‘/api’, router1); • /api/user routes will be created
  • 68. Multiple Environments • Common configuration • Environment specific • development • production • Environment variables + configured constants • Secure Info -> Environment Variables • Otherwise, in code, checked in
  • 69. What can you configure? • DB urls • application urls • social media integration • Anything and everything
  • 70. Middlewares • Extension, without inheritance • Layered approach • Decide if ok to proceed • or skip to error
  • 71. Code Along Step 11 - Use nested routers Step 12 - Understanding middlewares
  • 72. Step 11 – Use nested routers • Create stocks.routes.js, user.routes.js • var express = require(‘express’); • var router = express.Router() • router.get(‘/’, function(req, res) {}); • module.exports = function(app) { app.use(‘/path’, router); }
  • 73. Step 12 – Understanding Middleware • function(req, res) {} • function(req, res, next) {} • What’s next? • Common Error Handling • function(err, req, res, next) {} • Ordering is important!
  • 74. Configuration in NodeJS • JSON Config files • One per environment, one global • Set environment variable before running app • Read from process.env • Load file • export
  • 75. A note about authentication • Don’t reinvent the wheel • Connect -> Middleware for common use cases • Passport -> Out of the box authentication framework for NodeJS & Express • Support for DB backed • FB, Google, Twitter OAuth • And more!
  • 76. Agenda • Working with MongoDB & SQL • Build & Deploy • Best Practices • Further Readings
  • 77. Using Databases • MongoDB -> JSON object store • SQL -> not natively JSON • Use ORMs when possible
  • 78. When does NoSQL make sense? • Non relational data • Transactions not required • Atomic, single document commits • Fast!!! • Document store
  • 79. Mongoose for MongoDB • ORM layer for MongoDB • Define • Schemas • Validations • Pre/post save hooks • Querying capabilities
  • 80. Code Along Step 13 - Switch to MongoDB
  • 81. Step 13 – Using MongoDB • Create Schemas & Models (stocks.model.js) • var StockSchema = new mongoose.Schema({// def //}) • var StockModel = mongoose.model(‘Stock’, StockSchema); • Export it • Controller • Require model, and use find and findOne • Same callback structure • index.js • mongoose.connect('mongodb://jsfoo:jsfoo2015@ds049997.mongolab.com:4999 7/nodejsfoo')
  • 82. SQL in NodeJS • Sequelize • BookshelfJS • Both offer no MSSQL support • msnodesql • node-odbc • mssql-orm
  • 83. Debugging NodeJS • WebStorm • Debug mode • Create run configurations • Start debugging • Add breakpoints
  • 84. Debugging NodeJS • http://nodejs.org/api/debugger.htm • Manually – Add debugger statement to code – Run using node debug index.js – c, n, s, o • continue, next, step in, out – repl • evaluate commands on the fly
  • 85. Build & Deploy • Grunt / Gulp • Run the tests before deploying • No node_modules • Ship entire folder • Run npm install at installation location • Point at main entry point • Environment driven!
  • 86. Structuring your Express Codebase • Folders – api • route level • controller, spec, model, routes – auth • routes • strategies • common – config • passport • express • environment based – views – components
  • 87. Keeping the server running • NodeJS crashes and stops • Use forever • Or an external process to keep restarting it
  • 88. Best Practices • Structure, modules • Parallelize when possible • Think about it at every step • Use libraries like async, underscore • Search for existing npm packages • Use Middlewares • over calling functions in controllers and handlers • ^ or ~ versions in package.json • Otherwise keep it up to date on a monthly basis
  • 89. Best Practices • Follow the callback pattern • Don’t break the err, data structure in your code • Watch out for async behavior within loops • Closure, but extract functions instead of inline • Use javascriptlint • or something similar • Use forever, nodemon, or something similar • To ensure your app doesn’t crash and burn • Can use it locally as well Restart on file change
  • 90. Other Useful Libraries • async • underscore • RabbitMQ – for Queues and RPC Servers • SocketIO / SockJS
  • 92. AngularJS + NodeJS Chat App • Setup Socket Listeners and Posters on NodeJS • Using SocketIO • Client side already setup • io.on(‘connection’, function(socket) {}); • socket.on(‘event’, function(data) {}); • io.emit(‘event’, data) • broadcast to all!
  • 93. Further Reading • Clusters • RabbitMQ • SocketIO • vasync • More observable, async • restify • Pure RESTful services, not web apps
  • 94. Cluster Example var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); }
  • 95. Cluster Example - continued else { // Workers can share any TCP connection // In this case its a HTTP server http.createServer(function(req, res) { res.writeHead(200); res.end("hello worldn"); }).listen(8000); }
  • 96. How it works • Child processes spawned using fork • Communicate with parent using IPC • Pass server handles back and forth • Server.listen in child • Serializes arguments • Passes to master process • Handle to server created or passed to child • OS responsible for load balancing across processes sharing same resource
  • 98. Thank you • Contact • shyam@hopscotch.in • @omniscient1 • Come join me at Hopscotch if you want to work on exciting stuff with a great company! • WE ARE HIRING!
  • 99. Hopscotch in Brief • Customer focused, Content oriented, discovery oriented shopping experience for moms! • Not an Amazon/Flipkart model • Vertical focused • Great leadership team • Harvard, INSEAD, Amazon, Google… • Amazing investors • Eduardo (FB Co-founder), Velos Partners, and more! • Customer focused, smart and rapid growth • 20-30% month on month! • Scrappy, hacker oriented culture • Come be a part of something awesome!

Notas do Editor

  1. When this over previous? Large files, process info as and when available. Logs, etc.
  2. team.controller getTeams getTeam