SlideShare a Scribd company logo
1 of 37
Unit-2
Getting Input from User
Node.js Basics: Datatypes
Node.js is a cross-platform JavaScript runtime environment. It allows the
creation of scalable Web servers without threading and networking tools using
JavaScript and a collection of “modules” that handle various core
functionalities. It can make console-based and web-based node.js applications.
Datatypes: Node.js contains various types of data types similar to JavaScript.
• Boolean:
• Undefined
• Null
• String
• Number
Loose Typing: Node.js supports loose typing, it means you don’t need
to specify what type of information will be stored in a variable in
advance. We use var keyword in Node.js to declare any type of variable.
Example of Datatype:
// Variable store number data type // var a = 10;
var a = 35; // var a = 20;
console.log(typeof a); // console.log(a)
// Variable store string data type
a = “Lovely Professional University";
console.log(typeof a);
// Variable store Boolean data type
a = true;
console.log(typeof a);
// Variable store undefined (no value) data type
a = undefined;
Console.log(typeof a);
Objects & Functions
Node.js objects are same as JavaScript objects i.e. the objects are similar
to variable and it contains many values which are written as name: value
pairs. Name and value are separated by colon and every pair is separated
by comma.
Create an object of Student: Name, Branch, City and Mobile Number.
var university =
{
Name: "LPU",
Address: "Phagwara",
Contact: "+917018003845",
Email: mukesh.27406@lpu.ac.in
};
// Display the object information
console.log("Information of variable university:", university);
// Display the type of variable
console.log("Type of variable university:", typeof university);
Node.js Functions
Node.js functions are defined using function keyword then the name of
the function and parameters which are passed in the function. In
Node.js, we don’t have to specify datatypes for the parameters and
check the number of arguments received. Node.js functions follow
every rule which is there while writing JavaScript functions.
function
function multiply(num1, num2)
{
return num1 * num2;
}
var x = 2;
var y = 3;
console.log("Multiplication of", x, "and", y, "is", multiply(x, y));
String and String Functions
In Node.js we can make a variable as string by assigning a value either
by using single (‘ vvv ‘) or double (“ bbbbb”) quotes and it contains
many functions to manipulate to strings.
var x = "Welcome to Lovely Professional University";
var y = 'Node.js Tutorials';
var z = ['Lovely', 'Professional', 'University'];
console.log(x);
console.log(y);
console.log("Concat Using (+) :", (x + y));
console.log("Concat Using Function :", (x.concat(y)));
console.log("Split string: ", x.split(' '));
console.log("Join string: ", z.join(' '));
console.log("Char At Index 5: ", x.charAt(10));
Node.js Buffer
In node.js, we have a data type called “Buffer” to store a binary data and
it is useful when we are reading a data from files or receiving a packets
over network.
How to read command line arguments in Node.js ?
Command-line arguments (CLI) are strings of text used to pass
additional information to a program when an application is running
through the command line interface of an operating system. We can
easily read these arguments by the global object in node i.e.
process object.
Exp 1:
Step 1: Save a file as index.js and paste the below code inside the file.
var arguments = process.argv ;
console.log(arguments);
arguments:
0 1 2 3 4 5 -----
Arguments[0] = Path1, Arguments[1] = Path2
Step 2: Run index.js file using below command:
node index.js
The process.argv contains an array where the 0th index contains the
node executable path, 1st index contains the path to your current file and
then the rest index contains the passed arguments.
Path1 Path2 “20” “10” “5”
Exp 2: Program to add two numbers passed as arguments
Step 1: Save the file as index1.js and paste the below code inside the
file.
var arguments = process.argv
function add(a, b)
{
// To extract number from string
return parseInt(a)+parseInt(b)
}
var sum = add(arguments[2], arguments[3])
console.log("Addition of a and b is equal to ", sum)
var arg = process.argv
var i
console.log("Even numbers are:")
for (i=1;i<process.argv.length;i++)
{
if (arg[i]%2 == 0)
{
console.log(arg[i])
}
}
Counting Table
var arguments = process.argv
let i;
var mul=arguments[2]
for (let i=1; i<=10; i++)
{
console.log(mul + " * " + i + " = " + mul*i);
}
Step 2: Run index1.js file using below command:
node index1.js
So this is how we can handle arguments in Node.js. The args module is
very popular for handling command-line arguments. It provides various
features like adding our own command to work and so on.
There is a given object, write node.js program to print the given object's
properties, delete the second property and get length of the object.
var user =
{
First_Name: "John",
Last_Name: "Smith",
Age: "38",
Department: "Software"
};
console.log(user);
console.log(Object.keys(user).length);
delete user.last_name;
console.log(user);
console.log(Object.keys(user).length);
How do you iterate over the given array in node.js?
Node.js provides forEach()function that is used to iterate over items in a
given array.
const arr = ['fish', 'crab', 'dolphin', 'whale', 'starfish'];
arr.forEach(element =>
{
console.log(element);
});
Const is the variables declared with the keyword const that stores
constant values. const declarations are block-scoped i.e. we can access
const only within the block where it was declared. const cannot be updated
or re-declared i.e. const will be the same within its block and cannot be re-
declare or update.
Getting Input from User
The main aim of a Node.js application is to work as a backend technology
and serve requests and return response. But we can also pass inputs directly
to a Node.js application.
We can use readline-sync, a third-party module to accept user inputs in a
synchronous manner.
• Syntax: npm install readline-sync
This will install the readline-sync module dependency in your local npm
project.
Example 1: Create a file with the name "input.js". After creating
the file, use the command "node input.js" to run this code.
const readline = require("readline-sync");
console.log("Enter input : ")
// Taking a number input
let num = Number(readline.question());
let number = [];
for (let i = 0; i < num; i++) {
number.push(Number(readline.question()));
}
console.log(number);
Example 2: Create a file with the name "input.js". After creating the file,
use the command "node input.js" to run this code. input1.js
var readline = require('readline-sync');
var name = readline.question("What is your name?");
console.log("Hi " + name + ", nice to meet you.");
Node.js since version 7 provides the readline module to perform
exactly this: get input from a readable stream such as the process.stdin
stream, which during the execution of a Node.js program is the
terminal input, one line at a time. input.js
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
readline.question(`What's your name?`, name => {
console.log(`Hi ${name}!`);
readline.close();
})
You can install it using npm install inquirer, and then you can
replicate the above code like this: input.js
const inquirer = require('inquirer')
var questions = [{
type: 'input',
name: 'name',
message: "What's your name?"
}]
inquirer.prompt(questions).then(answers => {
console.log(`Hi ${answers['name']}!`)
})
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What is your name ? ", function(name) {
rl.question("Where do you live ? ", function(country) {
console.log(`${name}, is a citizen of ${country}`);
rl.close();
});
});
rl.on("close", function() {
console.log("nBYE BYE");
process.exit(0);
});
Question 1: Command to list all modules that are install globally?
• $ npm ls -g
• $ npm ls
• $ node ls -g
• $ node ls
Question 2: Which of the following module is required for path specific
operations ?
• Os module
• Path module
• Fs module
• All of the above.
Question 3: How do you install Nodemon using Node.js?
• npm install -g nodemon
• node install -g nodemon
Question 4: Which of the following is not a benefit of using modules?
• Provides a means of dividing up tasks
• Provides a means of reuse of program code
• Provides a means of reducing the size of the program
• Provides a means of testing individual parts of the program
Question 5: Command to show installed version of Node?
• $ npm --version
• $ node --version
• $ npm getVersion
• $ node getVersion
Question 6: Node.js uses an event-driven, non-blocking I/O model ?
• True
• False
Question 7: Node uses _________ engine in core.
• Chorme V8
• Microsoft Chakra
• SpiderMonkey
• Node En
Question 8: In which of the following areas, Node.js is perfect to use?
• I/O bound Applications
• Data Streaming Applications
• Data Intensive Realtime Applications DIRT
• All of the above.

More Related Content

Similar to Getting Input from User

How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js ModuleFred Chien
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScriptDenis Voituron
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
Node js
Node jsNode js
Node jshazzaz
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...Julia Cherniak
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩HyeonSeok Choi
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diplomamustkeem khan
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java scriptmichaelaaron25322
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 

Similar to Getting Input from User (20)

How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
Book
BookBook
Book
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Node js
Node jsNode js
Node js
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++Blazing Fast Windows 8 Apps using Visual C++
Blazing Fast Windows 8 Apps using Visual C++
 
Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩Node 관계형 데이터베이스_바인딩
Node 관계형 데이터베이스_바인딩
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 

More from Lovely Professional University

The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageLovely Professional University
 

More from Lovely Professional University (20)

The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
 
Working with JSON
Working with JSONWorking with JSON
Working with JSON
 
Yargs Module
Yargs ModuleYargs Module
Yargs Module
 
NODEMON Module
NODEMON ModuleNODEMON Module
NODEMON Module
 
fs Module.pptx
fs Module.pptxfs Module.pptx
fs Module.pptx
 
Transaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptxTransaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptx
 
web_server_browser.ppt
web_server_browser.pptweb_server_browser.ppt
web_server_browser.ppt
 
Web Server.pptx
Web Server.pptxWeb Server.pptx
Web Server.pptx
 
Number System.pptx
Number System.pptxNumber System.pptx
Number System.pptx
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
 
Information System.pptx
Information System.pptxInformation System.pptx
Information System.pptx
 
Applications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptxApplications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptx
 
Application of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptxApplication of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptx
 
Deploying your app.pptx
Deploying your app.pptxDeploying your app.pptx
Deploying your app.pptx
 
Setting up github and ssh keys.ppt
Setting up github and ssh keys.pptSetting up github and ssh keys.ppt
Setting up github and ssh keys.ppt
 
Adding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.pptAdding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.ppt
 
Requiring your own files.pptx
Requiring your own files.pptxRequiring your own files.pptx
Requiring your own files.pptx
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
Yargs Module.pptx
Yargs Module.pptxYargs Module.pptx
Yargs Module.pptx
 
Working with JSON.pptx
Working with JSON.pptxWorking with JSON.pptx
Working with JSON.pptx
 

Recently uploaded

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Recently uploaded (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

Getting Input from User

  • 2. Node.js Basics: Datatypes Node.js is a cross-platform JavaScript runtime environment. It allows the creation of scalable Web servers without threading and networking tools using JavaScript and a collection of “modules” that handle various core functionalities. It can make console-based and web-based node.js applications. Datatypes: Node.js contains various types of data types similar to JavaScript. • Boolean: • Undefined • Null • String • Number
  • 3. Loose Typing: Node.js supports loose typing, it means you don’t need to specify what type of information will be stored in a variable in advance. We use var keyword in Node.js to declare any type of variable.
  • 4. Example of Datatype: // Variable store number data type // var a = 10; var a = 35; // var a = 20; console.log(typeof a); // console.log(a) // Variable store string data type a = “Lovely Professional University"; console.log(typeof a); // Variable store Boolean data type a = true; console.log(typeof a); // Variable store undefined (no value) data type a = undefined; Console.log(typeof a);
  • 5. Objects & Functions Node.js objects are same as JavaScript objects i.e. the objects are similar to variable and it contains many values which are written as name: value pairs. Name and value are separated by colon and every pair is separated by comma. Create an object of Student: Name, Branch, City and Mobile Number.
  • 6. var university = { Name: "LPU", Address: "Phagwara", Contact: "+917018003845", Email: mukesh.27406@lpu.ac.in }; // Display the object information console.log("Information of variable university:", university); // Display the type of variable console.log("Type of variable university:", typeof university);
  • 7. Node.js Functions Node.js functions are defined using function keyword then the name of the function and parameters which are passed in the function. In Node.js, we don’t have to specify datatypes for the parameters and check the number of arguments received. Node.js functions follow every rule which is there while writing JavaScript functions. function
  • 8. function multiply(num1, num2) { return num1 * num2; } var x = 2; var y = 3; console.log("Multiplication of", x, "and", y, "is", multiply(x, y));
  • 9. String and String Functions In Node.js we can make a variable as string by assigning a value either by using single (‘ vvv ‘) or double (“ bbbbb”) quotes and it contains many functions to manipulate to strings.
  • 10. var x = "Welcome to Lovely Professional University"; var y = 'Node.js Tutorials'; var z = ['Lovely', 'Professional', 'University']; console.log(x); console.log(y); console.log("Concat Using (+) :", (x + y)); console.log("Concat Using Function :", (x.concat(y))); console.log("Split string: ", x.split(' ')); console.log("Join string: ", z.join(' ')); console.log("Char At Index 5: ", x.charAt(10));
  • 11. Node.js Buffer In node.js, we have a data type called “Buffer” to store a binary data and it is useful when we are reading a data from files or receiving a packets over network.
  • 12. How to read command line arguments in Node.js ? Command-line arguments (CLI) are strings of text used to pass additional information to a program when an application is running through the command line interface of an operating system. We can easily read these arguments by the global object in node i.e. process object.
  • 13. Exp 1: Step 1: Save a file as index.js and paste the below code inside the file. var arguments = process.argv ; console.log(arguments); arguments: 0 1 2 3 4 5 ----- Arguments[0] = Path1, Arguments[1] = Path2 Step 2: Run index.js file using below command: node index.js The process.argv contains an array where the 0th index contains the node executable path, 1st index contains the path to your current file and then the rest index contains the passed arguments. Path1 Path2 “20” “10” “5”
  • 14. Exp 2: Program to add two numbers passed as arguments Step 1: Save the file as index1.js and paste the below code inside the file. var arguments = process.argv function add(a, b) { // To extract number from string return parseInt(a)+parseInt(b) } var sum = add(arguments[2], arguments[3]) console.log("Addition of a and b is equal to ", sum)
  • 15. var arg = process.argv var i console.log("Even numbers are:") for (i=1;i<process.argv.length;i++) { if (arg[i]%2 == 0) { console.log(arg[i]) } }
  • 16. Counting Table var arguments = process.argv let i; var mul=arguments[2] for (let i=1; i<=10; i++) { console.log(mul + " * " + i + " = " + mul*i); }
  • 17. Step 2: Run index1.js file using below command: node index1.js So this is how we can handle arguments in Node.js. The args module is very popular for handling command-line arguments. It provides various features like adding our own command to work and so on.
  • 18. There is a given object, write node.js program to print the given object's properties, delete the second property and get length of the object. var user = { First_Name: "John", Last_Name: "Smith", Age: "38", Department: "Software" }; console.log(user); console.log(Object.keys(user).length); delete user.last_name; console.log(user); console.log(Object.keys(user).length);
  • 19. How do you iterate over the given array in node.js? Node.js provides forEach()function that is used to iterate over items in a given array. const arr = ['fish', 'crab', 'dolphin', 'whale', 'starfish']; arr.forEach(element => { console.log(element); }); Const is the variables declared with the keyword const that stores constant values. const declarations are block-scoped i.e. we can access const only within the block where it was declared. const cannot be updated or re-declared i.e. const will be the same within its block and cannot be re- declare or update.
  • 20. Getting Input from User The main aim of a Node.js application is to work as a backend technology and serve requests and return response. But we can also pass inputs directly to a Node.js application. We can use readline-sync, a third-party module to accept user inputs in a synchronous manner. • Syntax: npm install readline-sync This will install the readline-sync module dependency in your local npm project.
  • 21. Example 1: Create a file with the name "input.js". After creating the file, use the command "node input.js" to run this code. const readline = require("readline-sync"); console.log("Enter input : ") // Taking a number input let num = Number(readline.question()); let number = []; for (let i = 0; i < num; i++) { number.push(Number(readline.question())); } console.log(number);
  • 22.
  • 23. Example 2: Create a file with the name "input.js". After creating the file, use the command "node input.js" to run this code. input1.js var readline = require('readline-sync'); var name = readline.question("What is your name?"); console.log("Hi " + name + ", nice to meet you.");
  • 24.
  • 25. Node.js since version 7 provides the readline module to perform exactly this: get input from a readable stream such as the process.stdin stream, which during the execution of a Node.js program is the terminal input, one line at a time. input.js const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }) readline.question(`What's your name?`, name => { console.log(`Hi ${name}!`); readline.close(); })
  • 26.
  • 27. You can install it using npm install inquirer, and then you can replicate the above code like this: input.js const inquirer = require('inquirer') var questions = [{ type: 'input', name: 'name', message: "What's your name?" }] inquirer.prompt(questions).then(answers => { console.log(`Hi ${answers['name']}!`) })
  • 28.
  • 29. const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("What is your name ? ", function(name) { rl.question("Where do you live ? ", function(country) { console.log(`${name}, is a citizen of ${country}`); rl.close(); }); }); rl.on("close", function() { console.log("nBYE BYE"); process.exit(0); });
  • 30. Question 1: Command to list all modules that are install globally? • $ npm ls -g • $ npm ls • $ node ls -g • $ node ls
  • 31. Question 2: Which of the following module is required for path specific operations ? • Os module • Path module • Fs module • All of the above.
  • 32. Question 3: How do you install Nodemon using Node.js? • npm install -g nodemon • node install -g nodemon
  • 33. Question 4: Which of the following is not a benefit of using modules? • Provides a means of dividing up tasks • Provides a means of reuse of program code • Provides a means of reducing the size of the program • Provides a means of testing individual parts of the program
  • 34. Question 5: Command to show installed version of Node? • $ npm --version • $ node --version • $ npm getVersion • $ node getVersion
  • 35. Question 6: Node.js uses an event-driven, non-blocking I/O model ? • True • False
  • 36. Question 7: Node uses _________ engine in core. • Chorme V8 • Microsoft Chakra • SpiderMonkey • Node En
  • 37. Question 8: In which of the following areas, Node.js is perfect to use? • I/O bound Applications • Data Streaming Applications • Data Intensive Realtime Applications DIRT • All of the above.