SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
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
Tom Croucher
 
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
 

Tendances (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
 

Similaire à Node.js System: The Approach

nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
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
Cosmin 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
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3
HyeonSeok Choi
 

Similaire à 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
 

Plus 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
 

Dernier

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
+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
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Dernier (20)

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
+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...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 

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