SlideShare uma empresa Scribd logo
1 de 19
Node JS For Starters
Design, implement and deploy a web service in mere minutes
Take that, JAVA!
What is Node?
● Node is a server that runs JS -
imagine a headless chrome on a
remote machine and that’s it (it does
use chrome’s v8 engine to run JS)
● Script is run in an event-driven non-
blocking loop
● It’s great for asynchronous tasks
● NodeJS is really just javascript
running on the server, so you get all
the goodies JS provides, and more
The Bad
● CPU intensive
● Not scalable by itself (however we
can scale by reverse proxying
multiple node instances to nginx -
just ask Duran how)
● It’s very low level - you do need to
worry about things like memory
leaks and error handling -
otherwise these will break your app
The Good
● A familiar language (it’s really just
JavaScript)
● Non-blocking functional language
● Ability to share codes between
frontend (browser) and backend
(server)
● NPM package manager
● Projects everywhere on git,
everywhere people!
Hello, world.
The code
hello.js
console.log('hello world');
The command
node hello.js
… yes, you can use it to write little command line tools, just ask me how after this
Let’s talk structure
A typical nodejs app consists of:
● An entry point (usually index.js)
● A package.json file for dependencies and project details
● A node_modules directory where the dependencies will be stored (vendors
directory for php coders)
● A src or app directory for your own code source (I prefer app - I keep src for
resources that need build)
● A .gitignore, of course, and don’t forget your readme.md too.
Dependencies Management
Nodejs dependencies are managed via npm, through the package.json file. There are 2
sections:
● dependencies - required for the app
● devDependencies - optional for development only
E.g.
"devDependencies": {
"chai": "^3.5.0",
"mocha": "^2.4.5",
"uglify-js": "^2.6.1",
},
"dependencies": {
"async": "^2.0.0-rc.5"
}
Our first NodeJS web service!
Now let’s try to make a little web service that takes 2 numbers and return the result of
first number multiplying the second one, and we’ll make:
● The web service itself that takes input and sends out json outputs
● A little module that does the calculation
We’ll also need to manage the different configurations for different environments, and
A package for unit tests, but we’ll get on those later.
Embrace Express
We use express package for the server:
npm install --save --save-exact express
And with just a few lines it’s up and running:
Set up a service for multiplications!
Math is hard, so we need a dedicated service for this thingy:
File: app/service/multiply.js
Content:
Pretty hardcore right?
And what is this `module.exports` thingy?
It’s really a wrapper - your code will be exposed via module.exports, and by NOT putting functions in
module.exports you can essentially create ‘private’ functions - we can chat more on this after the session.
Put it all together
Here’s how we include our packages:
And here’s how we route a nice url /X/x/Y
Run it
Let’s say we want to run it on port 1200:
PORT=1200 node index.js
Want fancy? Put it in package.json
"start": "PORT=1200 node index.js",
And we can run by
npm start
So far we’ve been on the synchronous side of the operation: output is sent immediately
once input is processed, but sometimes it may take a while to process something, but
you want to give the user instant feedback (that you are on it), here’s the little trick:
You can continue doing stuff after response is sent - node js is after all, javascript; by
nature, it allows for operation to happen continuously (try it in browser if you don’t
believe me). Note: for async operations, I have a nice bonus page after this, stay tuned.
Immediate Response & work in background
NodeJS best practices
I’ll list only a few here, for the full list go here: https://devcenter.heroku.com/articles/node-best-practices
● Always start project with npm init.
● Adapt to ECMAScript6 standards (https://nodejs.org/en/docs/es6/), you can thank
me later when you start learning modern languages such as swift.
● Keep all lib file names in lowercase and use dash(-) instead of camel case, e.g.
service-sapi.js
● Use 2 spaces indentation (BTW, for php, please use PSR2 - 4 spaces unless you are
in drupal…)
● It’s better to fix the version of your dependencies (Duran/Lito will be super happy if
Bonus content: Heroku the free playground
Sign up on Heroku.com and you can deploy in mere minutes.
Go to the project, and all you need to do:
See it in action:
Bonus content: universal JS
Yes we can make our node js modules compatible with both browser and server-side,
all we need to do is to use window object reference and assign also to the module
exports. See code below:
1. Always use IIFE (immediately invoked
function expression) to enclose it for
isolation on browser (not required for
node)
2. Verify if module exists before assigning
to module.exports
3. Use (this) to make `window` available
from server-side to avoid syntax errorQuizz: what is ‘window’ object
in server mode?
Bonus content: unit tests
Toolset:
Prerequisite:
npm install -g mocha
Bonus content: Async calls
Enough talk, let’s code:
Useful resources
Deploy nodejs app with heroku
https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction
Free mongodb host (up to 500mb storage, perfect for personal projects)
https://mlab.com/
NPM
https://www.npmjs.com/
Best practice (actual practical advice)
https://github.com/mattdesl/module-best-practices
Udemy Course:
https://www.udemy.com/nodejs-for-beginning-programmers-100-practical/
Dora the explorer...
Beginners:
● Find out how to serve static web pages
● Write a piece of code that connects to a mongodb instance
ABOVE & BEYOND:
● Rewrite the editorial review page with nodejs
● Rewrite the BAC search results page with nodejs

Mais conteúdo relacionado

Mais procurados

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
 
3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don'tF5 Buddy
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.jsvaluebound
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS Ganesh Kondal
 
Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHPLee Boynton
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJSJITENDRA KUMAR PATEL
 
Vagrant plugin development intro
Vagrant plugin development introVagrant plugin development intro
Vagrant plugin development introBudh Ram Gurung
 
Nodejs Intro - Part2 Introduction to Web Applications
Nodejs Intro - Part2 Introduction to Web ApplicationsNodejs Intro - Part2 Introduction to Web Applications
Nodejs Intro - Part2 Introduction to Web ApplicationsBudh Ram Gurung
 
Overview: How to Measure your WebApp
Overview: How to Measure your WebAppOverview: How to Measure your WebApp
Overview: How to Measure your WebAppChang W. Doh
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBhargav Anadkat
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node jsAkshay Mathur
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystemYukti Kaura
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptLars Thorup
 

Mais procurados (20)

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
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't3 Things Everyone Knows About Node JS That You Don't
3 Things Everyone Knows About Node JS That You Don't
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.js
 
NodeJS - Server Side JS
NodeJS - Server Side JS NodeJS - Server Side JS
NodeJS - Server Side JS
 
Integrating Node.js with PHP
Integrating Node.js with PHPIntegrating Node.js with PHP
Integrating Node.js with PHP
 
Node js
Node jsNode js
Node js
 
Future of NodeJS
Future of NodeJSFuture of NodeJS
Future of NodeJS
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Vagrant plugin development intro
Vagrant plugin development introVagrant plugin development intro
Vagrant plugin development intro
 
Nodejs Intro - Part2 Introduction to Web Applications
Nodejs Intro - Part2 Introduction to Web ApplicationsNodejs Intro - Part2 Introduction to Web Applications
Nodejs Intro - Part2 Introduction to Web Applications
 
Overview: How to Measure your WebApp
Overview: How to Measure your WebAppOverview: How to Measure your WebApp
Overview: How to Measure your WebApp
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
 
Node
NodeNode
Node
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
 
Node js
Node jsNode js
Node js
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
 

Semelhante a Nodejs web service for starters

Node js (runtime environment + js library) platform
Node js (runtime environment + js library) platformNode js (runtime environment + js library) platform
Node js (runtime environment + js library) platformSreenivas Kappala
 
OSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshopOSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshopleffen
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architectureBen Lin
 
Introduction to node.js By Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed AssafAhmed Assaf
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJSHüseyin BABAL
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JSFestUA
 
JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendVlad Fedosov
 
Django simplified : by weever mbakaya
Django simplified : by weever mbakayaDjango simplified : by weever mbakaya
Django simplified : by weever mbakayaMbakaya Kwatukha
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Fwdays
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.jsMd. Sohel Rana
 
Riereta Node.js session 3 (with notes)
Riereta Node.js session 3 (with notes)Riereta Node.js session 3 (with notes)
Riereta Node.js session 3 (with notes)Tekno Paul
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Ganesh Kondal
 

Semelhante a Nodejs web service for starters (20)

Nodejs
NodejsNodejs
Nodejs
 
Nodejs
NodejsNodejs
Nodejs
 
02 Node introduction
02 Node introduction02 Node introduction
02 Node introduction
 
Node js (runtime environment + js library) platform
Node js (runtime environment + js library) platformNode js (runtime environment + js library) platform
Node js (runtime environment + js library) platform
 
OSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshopOSDC.no 2015 introduction to node.js workshop
OSDC.no 2015 introduction to node.js workshop
 
Webconf nodejs-production-architecture
Webconf nodejs-production-architectureWebconf nodejs-production-architecture
Webconf nodejs-production-architecture
 
Introduction to node.js By Ahmed Assaf
Introduction to node.js  By Ahmed AssafIntroduction to node.js  By Ahmed Assaf
Introduction to node.js By Ahmed Assaf
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
 
JSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontendJSFest 2019: Technology agnostic microservices at SPA frontend
JSFest 2019: Technology agnostic microservices at SPA frontend
 
Django simplified : by weever mbakaya
Django simplified : by weever mbakayaDjango simplified : by weever mbakaya
Django simplified : by weever mbakaya
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
NodeJS @ ACS
NodeJS @ ACSNodeJS @ ACS
NodeJS @ ACS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"Philip Shurpik "Architecting React Native app"
Philip Shurpik "Architecting React Native app"
 
Introduction to node.js
Introduction to  node.jsIntroduction to  node.js
Introduction to node.js
 
Node.js.pdf
Node.js.pdfNode.js.pdf
Node.js.pdf
 
Riereta Node.js session 3 (with notes)
Riereta Node.js session 3 (with notes)Riereta Node.js session 3 (with notes)
Riereta Node.js session 3 (with notes)
 
Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6Tech io nodejs_20130531_v0.6
Tech io nodejs_20130531_v0.6
 

Último

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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
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
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Último (20)

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...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
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 ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
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
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

Nodejs web service for starters

  • 1. Node JS For Starters Design, implement and deploy a web service in mere minutes Take that, JAVA!
  • 2. What is Node? ● Node is a server that runs JS - imagine a headless chrome on a remote machine and that’s it (it does use chrome’s v8 engine to run JS) ● Script is run in an event-driven non- blocking loop ● It’s great for asynchronous tasks ● NodeJS is really just javascript running on the server, so you get all the goodies JS provides, and more
  • 3. The Bad ● CPU intensive ● Not scalable by itself (however we can scale by reverse proxying multiple node instances to nginx - just ask Duran how) ● It’s very low level - you do need to worry about things like memory leaks and error handling - otherwise these will break your app The Good ● A familiar language (it’s really just JavaScript) ● Non-blocking functional language ● Ability to share codes between frontend (browser) and backend (server) ● NPM package manager ● Projects everywhere on git, everywhere people!
  • 4. Hello, world. The code hello.js console.log('hello world'); The command node hello.js … yes, you can use it to write little command line tools, just ask me how after this
  • 5. Let’s talk structure A typical nodejs app consists of: ● An entry point (usually index.js) ● A package.json file for dependencies and project details ● A node_modules directory where the dependencies will be stored (vendors directory for php coders) ● A src or app directory for your own code source (I prefer app - I keep src for resources that need build) ● A .gitignore, of course, and don’t forget your readme.md too.
  • 6. Dependencies Management Nodejs dependencies are managed via npm, through the package.json file. There are 2 sections: ● dependencies - required for the app ● devDependencies - optional for development only E.g. "devDependencies": { "chai": "^3.5.0", "mocha": "^2.4.5", "uglify-js": "^2.6.1", }, "dependencies": { "async": "^2.0.0-rc.5" }
  • 7. Our first NodeJS web service! Now let’s try to make a little web service that takes 2 numbers and return the result of first number multiplying the second one, and we’ll make: ● The web service itself that takes input and sends out json outputs ● A little module that does the calculation We’ll also need to manage the different configurations for different environments, and A package for unit tests, but we’ll get on those later.
  • 8. Embrace Express We use express package for the server: npm install --save --save-exact express And with just a few lines it’s up and running:
  • 9. Set up a service for multiplications! Math is hard, so we need a dedicated service for this thingy: File: app/service/multiply.js Content: Pretty hardcore right? And what is this `module.exports` thingy? It’s really a wrapper - your code will be exposed via module.exports, and by NOT putting functions in module.exports you can essentially create ‘private’ functions - we can chat more on this after the session.
  • 10. Put it all together Here’s how we include our packages: And here’s how we route a nice url /X/x/Y
  • 11. Run it Let’s say we want to run it on port 1200: PORT=1200 node index.js Want fancy? Put it in package.json "start": "PORT=1200 node index.js", And we can run by npm start
  • 12. So far we’ve been on the synchronous side of the operation: output is sent immediately once input is processed, but sometimes it may take a while to process something, but you want to give the user instant feedback (that you are on it), here’s the little trick: You can continue doing stuff after response is sent - node js is after all, javascript; by nature, it allows for operation to happen continuously (try it in browser if you don’t believe me). Note: for async operations, I have a nice bonus page after this, stay tuned. Immediate Response & work in background
  • 13. NodeJS best practices I’ll list only a few here, for the full list go here: https://devcenter.heroku.com/articles/node-best-practices ● Always start project with npm init. ● Adapt to ECMAScript6 standards (https://nodejs.org/en/docs/es6/), you can thank me later when you start learning modern languages such as swift. ● Keep all lib file names in lowercase and use dash(-) instead of camel case, e.g. service-sapi.js ● Use 2 spaces indentation (BTW, for php, please use PSR2 - 4 spaces unless you are in drupal…) ● It’s better to fix the version of your dependencies (Duran/Lito will be super happy if
  • 14. Bonus content: Heroku the free playground Sign up on Heroku.com and you can deploy in mere minutes. Go to the project, and all you need to do: See it in action:
  • 15. Bonus content: universal JS Yes we can make our node js modules compatible with both browser and server-side, all we need to do is to use window object reference and assign also to the module exports. See code below: 1. Always use IIFE (immediately invoked function expression) to enclose it for isolation on browser (not required for node) 2. Verify if module exists before assigning to module.exports 3. Use (this) to make `window` available from server-side to avoid syntax errorQuizz: what is ‘window’ object in server mode?
  • 16. Bonus content: unit tests Toolset: Prerequisite: npm install -g mocha
  • 17. Bonus content: Async calls Enough talk, let’s code:
  • 18. Useful resources Deploy nodejs app with heroku https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction Free mongodb host (up to 500mb storage, perfect for personal projects) https://mlab.com/ NPM https://www.npmjs.com/ Best practice (actual practical advice) https://github.com/mattdesl/module-best-practices Udemy Course: https://www.udemy.com/nodejs-for-beginning-programmers-100-practical/
  • 19. Dora the explorer... Beginners: ● Find out how to serve static web pages ● Write a piece of code that connects to a mongodb instance ABOVE & BEYOND: ● Rewrite the editorial review page with nodejs ● Rewrite the BAC search results page with nodejs