SlideShare a Scribd company logo
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);
Getting Input from User
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.");
Getting Input from User
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();
})
Getting Input from User
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']}!`)
})
Getting Input from User
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.
Ad

More Related Content

Similar to Getting Input from User (20)

Book
BookBook
Book
luis_lmro
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
Denis Voituron
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
Java Programming Tutorials Basic to Advanced 2
Java Programming Tutorials Basic to Advanced 2Java Programming Tutorials Basic to Advanced 2
Java Programming Tutorials Basic to Advanced 2
JALALUDHEENVK1
 
Node js
Node jsNode js
Node js
hazzaz
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
Knoldus Inc.
 
Unit-3.pptx node js ppt documents semester-5
Unit-3.pptx node js ppt documents semester-5Unit-3.pptx node js ppt documents semester-5
Unit-3.pptx node js ppt documents semester-5
makanijenshi2409
 
"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 Stack
Troy Miles
 
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++
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
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 Mizrahi
Ran Mizrahi
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
node.js.pptx
node.js.pptxnode.js.pptx
node.js.pptx
rani marri
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
mustkeem khan
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Somkiat Puisungnoen
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
Hussain Behestee
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
michaelaaron25322
 
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
Adam Getchell
 
A la découverte de TypeScript
A la découverte de TypeScriptA la découverte de TypeScript
A la découverte de TypeScript
Denis Voituron
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
Java Programming Tutorials Basic to Advanced 2
Java Programming Tutorials Basic to Advanced 2Java Programming Tutorials Basic to Advanced 2
Java Programming Tutorials Basic to Advanced 2
JALALUDHEENVK1
 
Node js
Node jsNode js
Node js
hazzaz
 
Unit-3.pptx node js ppt documents semester-5
Unit-3.pptx node js ppt documents semester-5Unit-3.pptx node js ppt documents semester-5
Unit-3.pptx node js ppt documents semester-5
makanijenshi2409
 
"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 Stack
Troy 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 Mizrahi
Ran Mizrahi
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Java Practical File Diploma
Java Practical File DiplomaJava Practical File Diploma
Java Practical File Diploma
mustkeem khan
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
michaelaaron25322
 
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
Adam Getchell
 

More from Lovely Professional University (20)

Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Lovely Professional University
 
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
Lovely Professional University
 
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
Lovely Professional University
 
Programme Management & Project Evaluation
Programme Management & Project EvaluationProgramme Management & Project Evaluation
Programme Management & Project Evaluation
Lovely Professional University
 
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
Lovely Professional University
 
Introduction to Software Project Management:
Introduction to Software Project Management:Introduction to Software Project Management:
Introduction to Software Project Management:
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 language
Lovely Professional University
 
Working with JSON
Working with JSONWorking with JSON
Working with JSON
Lovely Professional University
 
Yargs Module
Yargs ModuleYargs Module
Yargs Module
Lovely Professional University
 
NODEMON Module
NODEMON ModuleNODEMON Module
NODEMON Module
Lovely Professional University
 
fs Module.pptx
fs Module.pptxfs Module.pptx
fs Module.pptx
Lovely Professional University
 
Transaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptxTransaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptx
Lovely Professional University
 
web_server_browser.ppt
web_server_browser.pptweb_server_browser.ppt
web_server_browser.ppt
Lovely Professional University
 
Web Server.pptx
Web Server.pptxWeb Server.pptx
Web Server.pptx
Lovely Professional University
 
Number System.pptx
Number System.pptxNumber System.pptx
Number System.pptx
Lovely Professional University
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
Lovely Professional University
 
Information System.pptx
Information System.pptxInformation System.pptx
Information System.pptx
Lovely Professional University
 
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
Lovely Professional University
 
Application of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptxApplication of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptx
Lovely Professional University
 
Deploying your app.pptx
Deploying your app.pptxDeploying your app.pptx
Deploying your app.pptx
Lovely Professional University
 
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Lovely Professional University
 
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
Lovely Professional University
 
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
Lovely Professional University
 
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
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 language
Lovely Professional University
 
Ad

Recently uploaded (20)

Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Building the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdfBuilding the Customer Identity Community, Together.pdf
Building the Customer Identity Community, Together.pdf
Cheryl Hung
 
Ad

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);
  • 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.");
  • 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(); })
  • 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']}!`) })
  • 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.
  翻译: