SlideShare a Scribd company logo
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

More Related Content

What's hot

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
Fabien Vauchelles
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
Arvind Devaraj
 
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
F5 Buddy
 
An overview of node.js
An overview of node.jsAn overview of node.js
An overview of node.js
valuebound
 
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
 
Future of NodeJS
Future of NodeJSFuture of NodeJS
Future of NodeJS
Sébastien Pertus
 
Introduction to node.js aka NodeJS
Introduction to node.js aka NodeJSIntroduction to node.js aka NodeJS
Introduction to node.js aka NodeJS
JITENDRA KUMAR PATEL
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
Budh Ram Gurung
 
Vagrant plugin development intro
Vagrant plugin development introVagrant plugin development intro
Vagrant plugin development intro
Budh 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 Applications
Budh Ram Gurung
 
Overview: How to Measure your WebApp
Overview: How to Measure your WebAppOverview: How to Measure your WebApp
Overview: How to Measure your WebApp
Chang W. Doh
 
Basic Concept of Node.js & NPM
Basic Concept of Node.js & NPMBasic Concept of Node.js & NPM
Basic Concept of Node.js & NPM
Bhargav Anadkat
 
Node
NodeNode
NodeJS
NodeJSNodeJS
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
NodeJS ecosystem
NodeJS ecosystemNodeJS ecosystem
NodeJS ecosystem
Yukti Kaura
 
Continuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScriptContinuous Integration for front-end JavaScript
Continuous Integration for front-end JavaScript
Lars Thorup
 

What's hot (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
 

Similar to Nodejs web service for starters

Nodejs
NodejsNodejs
Nodejs
NodejsNodejs
Nodejs
dssprakash
 
02 Node introduction
02 Node introduction02 Node introduction
02 Node introduction
Ahmed Elbassel
 
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
Sreenivas 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 workshop
leffen
 
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 Assaf
Ahmed Assaf
 
Complete MVC on NodeJS
Complete MVC on NodeJSComplete MVC on NodeJS
Complete MVC on NodeJS
Hüseyin BABAL
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
Kalp 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 frontend
Vlad Fedosov
 
Django simplified : by weever mbakaya
Django simplified : by weever mbakayaDjango simplified : by weever mbakaya
Django simplified : by weever mbakaya
Mbakaya Kwatukha
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
Chris Cowan
 
NodeJS @ ACS
NodeJS @ ACSNodeJS @ ACS
NodeJS @ ACS
Mauro Parra-Miranda
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash 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.js
Md. Sohel Rana
 
Node.js.pdf
Node.js.pdfNode.js.pdf
Node.js.pdf
gulfam ali
 
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.6
Ganesh Kondal
 

Similar to 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
 

Recently uploaded

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 

Recently uploaded (20)

Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 

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