SlideShare uma empresa Scribd logo
1 de 10
Node.js System:
The Approach
Haci M. Yaman
26/4/2021
Content
1. Introduction
2. Common Internal Node.js Modules
3. JavaScript on Node.js vs Java on JRE
4. Sample HTTP Server
5. External Modules/Libraries
6. Sample HTTP Server: updated
7. Sample CLI tool
8. The End with Links
1. Introduction
• an asynchronous event-driven JavaScript runtime built on Chrome's V8
JavaScript engine
• designed to build scalable network applications
• single-threaded and an event loop; avoiding multi-threaded networking
• JavaScript development from browser-side to server-side
• You can deliver systems that can share code on frontend and backend
• Active LTS: version to create stable apps using (almost) latest ECMAScript
• LTS: a version of Node.js with Long Term Support,
i.e. with a long maintenance period
• ECMAScript is a Standard for scripting languages such as JavaScript
• JavaScript is a language based on ECMAScript
Ref: https://nodejs.org/
2. Common Internal Node.js Modules
• Data:
• Buffer, Stream
• I/O:
• Console, File System, Path
• Networking:
• HTTP, HTTP/2, HTTPS, Net, Query String, URL
• Security:
• Crypto, TLS
• Uncategorized:
• Process, Timers, Utilities
Ref: https://nodejs.org/api/
3. JavaScript on Node.js vs Java on JRE
JavaScript on Node.js Java on JRE
Dynamically-typed
prototype-based
multi-paradigm
non-strict
Statically-typed
class-based
object-oriented
strict
https://en.wikipedia.org/wiki/JavaScript_syntax
https://www.w3schools.com/js/js_syntax.asp
https://en.wikipedia.org/wiki/Java_syntax
https://www.w3schools.com/java/java_syntax.asp
4. Sample HTTP Server
const http = require('http'); // load internal Node.js module
const hostname = '127.0.0.1', port = 3000; // prepare constants for hostname and port
let requestCounter = 0; // define and initialize request counter
/**
* Handle incoming HTTP request and respond
* @param {http.IncomingMessage} request
* @param {http.ServerResponse} response
* @returns {void}
*/
function handleRequest(request, response) {
requestCounter++; // increment request counter
response.statusCode = 200; // set HTTP status code of response
response.setHeader('Content-Type', 'text/plain'); // set HTTP header
response.end('Hello World'); // send string message and finish responding
// this function does not return any value
}
// create an instance of http.Server by calling helper function
const server = http.createServer(handleRequest); // callback using predefined function
// start listening to network on port 3000
server.listen(port, hostname, () => { // callback using lambda function
// once ready, inform user on console
console.log(`Server running at http://${hostname}:${port}/`);
});
5. External Modules/Libraries
• NPM: Node Package Manager
• npmjs.com: the world's largest software registry
• developers publish and share open-source Node modules
• package.json
• a meta data file for a Node.js project
• info like name, version, dependencies, scripts
• Start a new project:
• npm init
• Add modules
• npm install express
• Add scripts and use
• npm run start
Ref: https://www.npmjs.com/
Ref: NVM (Node Version Manager)
https://github.com/nvm-sh/nvm
6. Sample HTTP Server - updated
const express = require('express'); // load express module
const axios = require('axios'); // load axios module
const app = express(); // create an instance of express.Application
// run this file like this:
// WEATHER_API="https://goweather.herokuapp.com/weather/" node ./index.js
const { WEATHER_API } = process.env; // read environment setting
if (!WEATHER_API) throw new Error('WEATHER_API is required');
app.get('/', async function (req, res){ // handle HTTP GET requests on URI '/'
const { city = 'london' } = req.query; // read URL query parameter 'city'
const weather = await axios.get(`${WEATHER_API}${city}`);
const { temperature } = weather.data; // extract temperature from weather response body
res.send(temperature); // send temperature only
});
app.post('/echo', (req, res) => { // handle HTTP POST requests on URI '/echo'
res.json({ data: req.body }); // send JSON response with data we received
});
app.listen(3000); // start listening to network
// you can use: http://localhost:3000/?city=london
7. Sample CLI tool
const fs = require('fs/promises');
const path = require('path');
const { Command } = require('commander');
const cmd = (new Command()).version('1.0.0’)
.option('-d, --dir-name <dir>', 'directory path');
main()
.then(totalBytes => console.log(`total bytes ${totalBytes}`))
.catch(err => console.error(err.message));
async function main() {
cmd.parse(process.argv);
const { dirName } = cmd.opts();
const dir = path.resolve(dirName);
console.log(`working on ${dir}`);
const entries = await fs.readdir(dir, { withFileTypes: true }); // array of fs.Dirent objects
const files = entries.filter(e => e.isFile());
let totalBytes = 0;
for (const file of files) {
const buffer = await fs.readFile(path.resolve(dirName, file.name));
totalBytes += buffer.length;
}
return totalBytes;
}
// you can run: node ./index.js -d .
The End
Thank you
Recommended articles:
https://www.npmjs.com/package/express
https://www.npmjs.com/package/axios
https://www.npmjs.com/package/commander
https://www.30secondsofcode.org/
JS algorithms and data structures:
https://github.com/trekhleb/javascript-algorithms

Mais conteúdo relacionado

Mais procurados

Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsWinston Hsieh
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developerscacois
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Visual Engineering
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Dinh Pham
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node jsThomas Roch
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronouskang taehun
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 

Mais procurados (20)

Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Node.js Patterns for Discerning Developers
Node.js Patterns for Discerning DevelopersNode.js Patterns for Discerning Developers
Node.js Patterns for Discerning Developers
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Node.js essentials
 Node.js essentials Node.js essentials
Node.js essentials
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
OHHttpStubs
OHHttpStubsOHHttpStubs
OHHttpStubs
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Javascript asynchronous
Javascript asynchronousJavascript asynchronous
Javascript asynchronous
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Node.js
Node.jsNode.js
Node.js
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 

Semelhante a Node.js System: The Approach

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSCosmin Mereuta
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Nodejs first class
Nodejs first classNodejs first class
Nodejs first classFin Chen
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleGeoff Ballinger
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3HyeonSeok Choi
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 

Semelhante a Node.js System: The Approach (20)

Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Scalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JSScalable network applications, event-driven - Node JS
Scalable network applications, event-driven - Node JS
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Nodejs first class
Nodejs first classNodejs first class
Nodejs first class
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Node.js
Node.jsNode.js
Node.js
 
5.node js
5.node js5.node js
5.node js
 
Server Side? Swift
Server Side? SwiftServer Side? Swift
Server Side? Swift
 
08 ajax
08 ajax08 ajax
08 ajax
 
Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 

Mais de Haci Murat Yaman

The API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and ImplementationThe API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and ImplementationHaci Murat Yaman
 
The API Journey: from REST to GraphQL
The API Journey: from REST to GraphQLThe API Journey: from REST to GraphQL
The API Journey: from REST to GraphQLHaci Murat Yaman
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1Haci Murat Yaman
 
The Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno landThe Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno landHaci Murat Yaman
 

Mais de Haci Murat Yaman (6)

MQTT meets AMQP
MQTT meets AMQPMQTT meets AMQP
MQTT meets AMQP
 
The API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and ImplementationThe API Journey: GraphQL Specification and Implementation
The API Journey: GraphQL Specification and Implementation
 
The API Journey: from REST to GraphQL
The API Journey: from REST to GraphQLThe API Journey: from REST to GraphQL
The API Journey: from REST to GraphQL
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1The Saga of JavaScript and TypeScript: Part 1
The Saga of JavaScript and TypeScript: Part 1
 
The Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno landThe Saga of JavaScript and Typescript: in Deno land
The Saga of JavaScript and Typescript: in Deno land
 

Último

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 

Último (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 

Node.js System: The Approach

  • 2. Content 1. Introduction 2. Common Internal Node.js Modules 3. JavaScript on Node.js vs Java on JRE 4. Sample HTTP Server 5. External Modules/Libraries 6. Sample HTTP Server: updated 7. Sample CLI tool 8. The End with Links
  • 3. 1. Introduction • an asynchronous event-driven JavaScript runtime built on Chrome's V8 JavaScript engine • designed to build scalable network applications • single-threaded and an event loop; avoiding multi-threaded networking • JavaScript development from browser-side to server-side • You can deliver systems that can share code on frontend and backend • Active LTS: version to create stable apps using (almost) latest ECMAScript • LTS: a version of Node.js with Long Term Support, i.e. with a long maintenance period • ECMAScript is a Standard for scripting languages such as JavaScript • JavaScript is a language based on ECMAScript Ref: https://nodejs.org/
  • 4. 2. Common Internal Node.js Modules • Data: • Buffer, Stream • I/O: • Console, File System, Path • Networking: • HTTP, HTTP/2, HTTPS, Net, Query String, URL • Security: • Crypto, TLS • Uncategorized: • Process, Timers, Utilities Ref: https://nodejs.org/api/
  • 5. 3. JavaScript on Node.js vs Java on JRE JavaScript on Node.js Java on JRE Dynamically-typed prototype-based multi-paradigm non-strict Statically-typed class-based object-oriented strict https://en.wikipedia.org/wiki/JavaScript_syntax https://www.w3schools.com/js/js_syntax.asp https://en.wikipedia.org/wiki/Java_syntax https://www.w3schools.com/java/java_syntax.asp
  • 6. 4. Sample HTTP Server const http = require('http'); // load internal Node.js module const hostname = '127.0.0.1', port = 3000; // prepare constants for hostname and port let requestCounter = 0; // define and initialize request counter /** * Handle incoming HTTP request and respond * @param {http.IncomingMessage} request * @param {http.ServerResponse} response * @returns {void} */ function handleRequest(request, response) { requestCounter++; // increment request counter response.statusCode = 200; // set HTTP status code of response response.setHeader('Content-Type', 'text/plain'); // set HTTP header response.end('Hello World'); // send string message and finish responding // this function does not return any value } // create an instance of http.Server by calling helper function const server = http.createServer(handleRequest); // callback using predefined function // start listening to network on port 3000 server.listen(port, hostname, () => { // callback using lambda function // once ready, inform user on console console.log(`Server running at http://${hostname}:${port}/`); });
  • 7. 5. External Modules/Libraries • NPM: Node Package Manager • npmjs.com: the world's largest software registry • developers publish and share open-source Node modules • package.json • a meta data file for a Node.js project • info like name, version, dependencies, scripts • Start a new project: • npm init • Add modules • npm install express • Add scripts and use • npm run start Ref: https://www.npmjs.com/ Ref: NVM (Node Version Manager) https://github.com/nvm-sh/nvm
  • 8. 6. Sample HTTP Server - updated const express = require('express'); // load express module const axios = require('axios'); // load axios module const app = express(); // create an instance of express.Application // run this file like this: // WEATHER_API="https://goweather.herokuapp.com/weather/" node ./index.js const { WEATHER_API } = process.env; // read environment setting if (!WEATHER_API) throw new Error('WEATHER_API is required'); app.get('/', async function (req, res){ // handle HTTP GET requests on URI '/' const { city = 'london' } = req.query; // read URL query parameter 'city' const weather = await axios.get(`${WEATHER_API}${city}`); const { temperature } = weather.data; // extract temperature from weather response body res.send(temperature); // send temperature only }); app.post('/echo', (req, res) => { // handle HTTP POST requests on URI '/echo' res.json({ data: req.body }); // send JSON response with data we received }); app.listen(3000); // start listening to network // you can use: http://localhost:3000/?city=london
  • 9. 7. Sample CLI tool const fs = require('fs/promises'); const path = require('path'); const { Command } = require('commander'); const cmd = (new Command()).version('1.0.0’) .option('-d, --dir-name <dir>', 'directory path'); main() .then(totalBytes => console.log(`total bytes ${totalBytes}`)) .catch(err => console.error(err.message)); async function main() { cmd.parse(process.argv); const { dirName } = cmd.opts(); const dir = path.resolve(dirName); console.log(`working on ${dir}`); const entries = await fs.readdir(dir, { withFileTypes: true }); // array of fs.Dirent objects const files = entries.filter(e => e.isFile()); let totalBytes = 0; for (const file of files) { const buffer = await fs.readFile(path.resolve(dirName, file.name)); totalBytes += buffer.length; } return totalBytes; } // you can run: node ./index.js -d .
  • 10. The End Thank you Recommended articles: https://www.npmjs.com/package/express https://www.npmjs.com/package/axios https://www.npmjs.com/package/commander https://www.30secondsofcode.org/ JS algorithms and data structures: https://github.com/trekhleb/javascript-algorithms