[go: up one dir, main page]

0% found this document useful (0 votes)
181 views91 pages

Fs QB: Question Bank and Answers

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 91

FS QB

Reference Links ku itha click karo

Question Bank and Answers

Write the structure of JavaScript


Data Types: Every Variable has a data type that tells what kind of data is being stored
in a variable. There are two types of data types in JavaScript namely Primitive data
types and Non-primitive data types.
Primitive data types: The predefined data types provided by JavaScript language are
known as primitive data types. Primitive data types are also known as in-built data
types.

Number

String

FS QB 1
undefined

Null

Boolean

Non-primitive data types: The data types that are derived from primitive data types of
the JavaScript language are known as non-primitive data types. It is also known as
derived data types or reference data types.

Object

Array

write a program JavaScript to find max. of three no. using math


object

// program to find the largest among three numbers


// take input from the user
const num1 = parseFloat(prompt("Enter first number: "));
const num2 = parseFloat(prompt("Enter second number: "));
const num3 = parseFloat(prompt("Enter third number: "));
const largest = Math.max(num1, num2, num3);
// display the result
alert("The largest number is " + largest);

Write a JS program to display a "Sona college of technology"


message on the browser.

alert("Sona college of technology");

FS QB 2
What are the limitations of in-browser JavaScript
JavaScript has no direct access to OS functions. It can’t read and write arbitrary
files on the hard disc, copy or execute them.

Different windows/tabs don’t recognize each other. JavaScript from one page is not
able to access the other one, in case they are from different sites. It’s known as
“Same Origin Policy”.

JavaScript allows communication over the net to the server from where the page
comes from. But, its capability of receiving data from the other site is prohibited.
That’s a safety limitation.

Write a JavaScript program to find the factorial of a given number.


function factorial(n){

    //base case

    if(n == 0 || n == 1){

        return 1;

    //recursive case

    }

else{

        return n * factorial(n-1);

    }

let n = 4;

answer = factorial(n)

alert("The factorial of " + n + " is " + answer);

What is NVM?
nvm is a version manager for node.js, designed to be installed per-user, and invoked
per-shell.  nvm  works on any POSIX-compliant shell (sh, dash, Ksh, zsh, bash), in

FS QB 3
particular on these platforms: unix, macOS, and windows WSL.
NVM allows users to:

Locally download any of the remote Long Term Support (LTS) versions of Node.js
with a simple command.

Easily switch between multiple versions of Node.js, right from the command line.

Set up aliases to switch between different downloaded versions of Node.js with


ease.

PART B

Develop a webpage that allows the user to enter details of the


passenger (name, age, email, gender). Write a client side scripting
code to validate the email, age and gender, where email should
consist of the special symbol @ and period(.), where age between
1 to 100 and gender is male or female.

<!DOCTYPE html>
<html>
<head>
<title>Student Information Form</title>
<script type="text/javascript">
function valid()
{
var na = document.getElementById("nm").value;
var ag = document.getElementById("age").value;
var ge = document.getElementById("gender").value;
var em = document.getElementById("eid").value.indexOf("@");
if(na==""||na==null)
{
alert("Enter The Name");
return false;
}
else if(isNaN(ag)||ag<1||ag>100)
{
alert("The age must be a number between 1 and 100");
return false;
}

FS QB 4
else if(ge==""||ge==null)
{
alert("Please Select Gender");
return false;
}
else if(em==-1)
{
alert("E-mail ID is not valid");
return false;
}
}
else
{
alert("The Student Information Submitted Successfully");
}
</script>
</head>
<body>
<center><b>
<h3>Student Information Form</h3>
<form action="" onsubmit="return valid()" method="post">
Name: <input type="text" id="nm"><br><br>
Age: <input type="text" id="age"><br><br>
<label for="gender">Please selecr your gender</label>
        <select id="gender">
            <option value="man">Man</option>
            <option value="woman" selected>Woman</option>
            <option value="other">Other</option>
        </select><br><br>
Email id: <input type="text" id="eid"><br><br>
<input type="submit" value="Submit">
</form>
</b></center>
</body>
</html>

Differentiate MERN from MEAN ?


MEAN MERN

Components include Mongo DB, Angular JS, Components include Mongo DB, React JS,
Express, and Node Express, and Node.

JavaScript development stack. Open source JavaScript library.

Uses Typescript language. Uses JavaScript and JSX.

FS QB 5
MEAN MERN

Component based architecture. None.

Regular DOM. Virtual DOM.

Bidirectional data flow. Unidirectional dataflow.

Differentiate NPM and NVM ?


NPM NVM

Npm is a package manager.


It let's you install software
(libraries, plugins,
Nvm is a nodejs version manager. It let's you easily install and
frameworks and
switch between versions. It retains globally installed packages for
applications). Typically this
each version.
software is installed to build
Node applications.
Sometimes it isn't.

Npm depends on Node. Nvm installs Node.

NPM is the official Node


NVM is the Node Version Manager. I wouldn’t personally
Package Manager (it’s not
recommend it because it does some funky things, but some
the only one), where “all”
people like it (I use one that’s just called n ). What it does is…
your Node packages live on
manage your Node version. Every once in a while, Node comes
the internet (a few years ago
out with a new version of the language and interpreter that
people started having issues
changes some things. A version manager lets you switch which
with how NPM does things,
version your computer is running. This is important because
and there were forks but
sometimes a Node program won’t actually run in a newer version
thankfully no knives). You
so you have to keep an older one around, but on the other hand,
can use NPM to install
some other Node program won’t run in the older version and
packages, publish packages,
needs the new one.
etc.

PART C

FS QB 6
Design a Passenger Registration form with First Name, Last name,
Address, City, State, Country, Pincode, Username and Password
fields for a General login webpage and satisfy the following
criteria:
(a) Check that the First Name, Last Name, City, Country, Username, and Password
fields are filled out.
(b) Check that the Pincode is exactly 6 numerics.

(c) Check that the state is exactly three characters.

(d) Check that the email is a valid email address

<HTML>
    <HEAD>
    <TITLE>WEB PAGE DESIGN WITH JAVA SCRIPT</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    function validate()
    {
        if(document.form1.fname.value.length==0)
        {
            alert("Enter first name");
            document.form1.fname.focus();
            return;
        }
        if(document.form1.lname.value.length==0)
        {
            alert("Enter last name");
            document.form1.lname.focus();
            return;
        }if(document.form1.uname.value.length==0)
        {
            alert("Enter user name");
            document.form1.uname.focus();
            return;
        }
        if(document.form1.pswrd.value.length==0)
        {
            alert("Enter password");
            document.form1.pswrd.focus();
            return;
        }
        if(document.form1.city.value.length==0)
        {
            alert("Enter the city");
            document.form1.city.focus();

FS QB 7
            return;
        } if(document.form1.country.value.length==0)
        {
            alert("Enter the country");
            document.form1.country.focus();
            return;
        }if(!document.form1.mail.includes('@'))
        {
            alert("Enter the valid email");
            document.form1.mail.focus();
            return;
        }
        document.writeln("<BODY><H1>SUCCESS!!</H1></BODY>");
    }
    </SCRIPT>
    </HEAD>
    <BODY>
    <FORM name="form1">
    <H1>Passenger Registration</H1>
    <HR></HR>
        FIRST NAME <INPUT type="text" name="fname" />
        LAST NAME  <INPUT type="text" name="lname" /> </br>
        ADDRESS <TEXTAREA rows="5" name="address"/></TEXTAREA> </br>
        CITY    <INPUT type="text" name="city" /> </br>
        STATE  <INPUT type="text" name="state" maxlength="3" /> </br>
        COUNTRY  <INPUT type="text" name="country" /> </br>
        PINCODE <INPUT type="text" name="pin" maxlength="6" /> </br>
        E-MAIL   <INPUT type="email" name="mail"/> </br>
        USERNAME <INPUT type="text" name="uname" />
        PASSWORD <INPUT type="password" name="pswrd" /> </br>
    <INPUT type="submit" value="SUBMIT" onclick="validate()">
    <INPUT type="reset" value="CLEAR"> </br>
    </FORM>
    </BODY>
    </HTML>

Design a webpage with a text box where the user can enter a four
digit number with a validation button. The digits entered here must
be in ascending order for the input (eg 1234,5678). Validate the
field using JavaScript.
<HTML>

    <HEAD>

    <TITLE>WEB PAGE DESIGN WITH JAVA SCRIPT</TITLE>

FS QB 8
    <SCRIPT LANGUAGE="JavaScript">

    function validate()

    {        var number = document.form1.number.value

       for(var i =1;i<number.length;i++){

            if(+number.charAt(i) < +number.charAt(i-1)){

                document.writeln("<BODY><H1>NOT VALID!!</H1></BODY>");

                return;

            }

        }

        document.writeln("<BODY><H1>VALID!!</H1></BODY>");

    }

    </SCRIPT>

    </HEAD>

    <BODY>

    <FORM name="form1">

    <H1>NUMBER CHECK</H1>

    <HR></HR>

        NUMBER <INPUT type="text" name="number" maxlength="4"/>

          <INPUT type="submit" value="VALIDATE" onclick="validate()" >

       </FORM>

    </BODY>

</HTML>

Create a Simple " Hello World!" message to deploy in react


application

import React from 'react';


import './App.css';
function App() {
    return (
      <h1> Hello World! </h1>
    );
}
export default App;

FS QB 9
Write JavaScript for the following.
Provide a text box for the user to enter username. Validate the user name must
contain eight characters. Provide submit button for the validation to happen. On
successful validation display a new page with an image and two textboxes for
entering width and height of the image respectively with a resize button at the
bottom of the image. On clicking the resize button validate the width and height
on successful validation display the image.

index.html

<!DOCTYPE html>
<html>
    <head>
    <title>WEB PAGE DESIGN WITH JAVA SCRIPT</title>
    <script language="JavaScript">
    function validate()
    {
        var name = document.form1.uname.value
        if(name.length !=8) {
            alert("Name must have 8 characters");
            return;
        }
        window.location.href = './imageScreen.html';
    }
    </script>
    </head>
    <body>
    <form name="form1">
    <h1>Name</h1>
    <hr>
    USERNAME <input type="text" name="uname" />
    <input type="submit" value="VALIDATE" onclick="validate()" >
    </form>
    </body>
</html>

imageScreen.html
<html>

    <head>

    <title>WEB PAGE DESIGN WITH JAVA SCRIPT</title>

FS QB 10
    <script language="JavaScript">

    function resize()   

        if(document.form1.weight.value >0 && document.form1.height.value> 0 )

var theImg = document.getElementById('img');

            theImg.style.height = document.form1.height.value;

            theImg.style.width = document.form1.weight.value;

        }

        event.preventDefault();

    }

    </script>

    </head>

    <body>

    <form name="form1">

    <h1>Image</h1>

    <hr>

    <img src="imgage.webp" alt="Girl in a jacket" width="500" height="300" id="img">


<br><br>

    WIDTH <input type="number" name="weight" />

    HEIGHT  <input type="number" name="height" />

<br>

    <input type="submit" value="RESIZE" onclick="resize()" >

       </form>

    </body>

</html>

How to setup React Environment on your Computer


Step 1: Install the latest version of NodeJS. Once we have set up NodeJS on our PC,
the next thing we need to do is set up React Boilerplate.
Step 2: Setting up react environment

npx create-react-app my-app

FS QB 11
You can run the project by typing the command cd my-app.

cd my-app
npm start

Step 3: Create a React app. Now to create an app we will use the boilerplate we
installed. The below command will create an app named myapp.
create-react-app myapp

Step 4: Start the development server. To start the development server, go inside your
current directory “myapp” and execute the below command:
npm start

1. What is the default local host port that a React development


server uses?

When we create a new react app using the npx create-react-app command, the default
port for the app is 3000. We can access the app from the localhost:3000.

2. What are the ways to create a generator functions?

The function* declaration ( function keyword followed by an asterisk) defines a


generator function, which returns a Generator object.

3. To develop and run React code, Node.js is required. True or


False? Justify.

FS QB 12
No, it doesn’t require Node.js, but it would be very difficult to build a project without it
since you need it to use almost all React libraries, which are Node.js packages.
Also, without Node.js, you can’t use Create React App, which makes creating the
project
and building very quick and easy.

4. Which keyword creates a constant in JavaScript?

ES6 provides a new way of declaring a constant by using the const keyword. The const
keyword creates a read-only reference to a value. By convention, the constant
identifiers
are in uppercase. Like the let keyword, the const keyword declares blocked-scope
variables.

5. What is GitHub?

GitHub is a code hosting platform for collaboration and version control. GitHub lets you
(and others) work together on projects. Sign up for GitHub at https://github.com/:
GitHub essentials are: Repositories.

6. What is called a copy of the 'real' DOM that is kept in memory?

In simple words, virtual DOM is just a copy of the original DOM kept in the memory and
synced with the real DOM by libraries such as ReactDOM. This process is called
Reconciliation. Virtual DOM has the same properties that of the Real DOM, but it lacks
the power to directly change the content of the screen.

FS QB 13
7. What is the correct command to create a new React project?

You create a new React project with the command create-react-app , followed by the
name of your project. For example: create-react-app my-app.

8. What does myReactApp refer to in the following command?


Ans: Project name

9. Enter the correct ReactDOM method to render the React element


to the
DOM:
ReactDOM.___________ (myElement,
document.getElementById('root'));

Ans: render

10. Differentiate Git and GitHub.

GitHub, meanwhile, serves as a host for Git repository teams to store their code in a
centralized location. While Git is a tool that's used to manage multiple versions of
source
code edits that are then transferred to files in a Git repository, GitHub serves as a
location for uploading copies of a Git repository.

11.What is a REPO in GitHub?

Repository: A directory or storage space where your projects can live. Sometimes

FS QB 14
GitHub
users shorten this to “repo.” It can be local to a folder on your computer, or it can be a
storage space on GitHub or another online host. You can keep code files, text files,
image
files, you name it, inside a repository.

12.What command is used to start the React local development


server?

You can run any one of the below mentioned commands to start the node server for
your ReactJS application:
npm run-script start.

npm run start.

npm start.

13. Write the step-by-step procedure to include React component


in your
webpage, without installing Node JS.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>React Local</title>
<!-- Import the React, React-Dom and Babel libraries from unpkg -->
<script type="application/javascript" src="https://unpkg.com/react@16.0.0/umd/react.prod
uction.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/react-dom@16.0.0/umd/react-
dom.production.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/babel-standalone@6.26.0/bab
el.js"></script>

FS QB 15
</head>

<body>
<div id="root"></div>

<script type="text/javascript">

</script>

</body>

</html>

14.Explain the step-by-step procedure to post a code in GitHub.

Steps are :
Initiate a local git repository on your computer.

git init

Add your remote repository.

git remote add origin [repo url]


git pull origin master

Start coding and add your files.

git add file1.js file2.js file3.js

Commit your code

git commit -m "Initial Commit”

Push your local repo state to your GitHub repo.

FS QB 16
git push origin master

15.Explain the step by step procedure to post a code in Github


using Command prompt.

Answer 14

16.Write a node.js server code to integrate with MySQL database


and do the following
operations.
a. Create a database of your own and insert the given into the
table.
b. Fetch the record based on:
● Joining the tables
● Recent data order
● Search criteria

const express = require("express");


const app = express();
const mysql = require('mysql');

const connection = mysql.createConnection({


host : 'localhost',
user : 'username',
password : 'password',
database : 'databasename'
});

FS QB 17
connection.connect((err) => {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255), createdDate DA
TETIME DEFAULT NOW())";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});

app.get("/insert",(req,res) => {
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});

app.get("/fetch",(req,res) => {
connection.query('SELECT * from users LIMIT 5 ORDER BY createdDate', (err, rows) => {
if(err) throw err;
console.log('The data from users table are: \n', rows);
res.send(rows);
});
});

app.listen(3000, () => {
console.log('Server is running at port 3000');
});

16. How can you check the installed version of Node JS?

Test Node. To see if Node is installed, open the Windows Command Prompt,
and type

node -v.

FS QB 18
This should print the version number so you’ll see something like this v0.10.35.

Test NPM. To see if NPM is installed, type

npm -v

This should print the version number so you’ll see something like this 1.4.28

Create a test file and run it. A simple way to test that node.js works is to
create a simple JavaScript file: name it hello.js, and just add the code
console.log('Node is installed!');.
To run the code simply open your command line program, navigate to the folder where
you save the file and type

node hello.js

This will start Node.js and run the code in the hello.js file.
You should see the output Node is installed!

17. Is NodeJS single threaded? How?

Reason behind node.js uses Single Threaded Event Loop Model architecture:

Initially, node.js was created as an experiment in asynchronous processing and in


theory was that doing asynchronous processing on a single thread could provide
more performance and scalability under typical web loads than the typical thread-

FS QB 19
based implementation when the application isn’t doing CPU intensive stuff and can
run thousands more concurrent connections than Apache or IIS or other thread-
based servers.

The single-threaded, asynchronous nature of node.js does also make things


complicated but threading is worse than this in terms of time taken to design an
application, cost of development, deadlocks, priority inversions, and all the other
things that come in the life cycle of an application.

There is also a very well known and criticized issue with the one thread per
request model for a server which is that they don’t scale very well for several
scenarios compared to the event loop thread model, in short, they lack scalability as
the application grows to meet the future demands and with the addition of new
features.

As Node.js follows Single-Threaded with Event Loop Model inspired by JavaScript


Event-based model with JavaScript callback mechanism. So, node.js is single-
threaded similar to JavaScript but not purely JavaScript code which implies things
that are done asynchronously like network calls, file system tasks, DNS lookup, etc.
are actually not handled by the main thread and are in C++ as Ryan Dahl is not a
fan of JavaScript and also C++ has access to multiple threads that makes it a better
language for asynchronous tasks.

18. Write the step – by –step procedure to build a Node.JS server


to verify a
given string a palindrome or not.

const express = require("express");


const app = express();
app.get("/checkPalindrome/", (req, res) => {
let string = req.query.string;
let len = string.length;
for (let i = 0; i < len / 2; i++) {
if (string[i] !== string[len - 1 - i]) {
return res.send("It is not a palindrome");
}
}
return res.send("It is a palindrome");
});

FS QB 20
app.listen(process.env.PORT || 3000, function () {
console.log(
"Express server listening on port %d in %s mode",
this.address().port,
app.settings.env
);
});

19.Write a Javascript code to make a function invoked (called)


when a button is clicked.

<body>
<button id="btn">Click me</button>
<script>
function test() {
alert("The function 'test' is executed");
}
let btn =document.getElementById("btn");
btn.addEventListener('click', event => {
test();
});
</script>
</body>

or

<body>
<button onclick="test()">Click me</button>
<script>
function test() {
alert("The function 'test' is executed");
}
</script>
</body>

FS QB 21
20.Write a node JS content script to send an email with default
content and
also another node.js script to retrieve email value from redis and
send the
current IP address of the email logged into the user as a mail.

const nodemailer = require("nodemailer");

async function main() {

let testAccount = await nodemailer.createTestAccount();

let transporter = nodemailer.createTransport({


host: "smtp.ethereal.email",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: testAccount.user,
pass: testAccount.pass,
},
});

👻
let info = await transporter.sendMail({
from: '"Fred Foo " foo@example.com', // sender address
to: "bar@example.com, baz@example.com", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>", // html body
});

console.log("Message sent: %s", info.messageId);

FS QB 22
console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
}

main().catch(console.error);

21.Differentiate Cluster and child_process modules in Node JS.

child processes
The  child_process  module provides the ability to spawn new processes which has their
own memory. The communication between these processes is established through IPC
(inter-process communication) provided by the operating system.
There are mainly three methods inside this module that we care about.

child_process.spawn()

child_process.fork()

child_process.exec()

Cluster
Cluster is mainly used for vertically (adding more power to your existing machine) scale
your nodejs web server. It is built on top of the child_process module. In an Http server,
the cluster module uses child_process.fork() to automatically fork processes and sets
up a master-slave architecture where the parent process distributes the incoming
request to the child processes in a round-robin fashion. Ideally, the number of
processes forked should be equal to the number of cpu cores your machine has.

22.Write the code to start serving static files in Express.js.

FS QB 23
Serving static files in Express
To serve static files such as images, CSS files, and JavaScript files, use
the  express.static  built-in middleware function in Express.

The function signature is:

express.static(root, [options])

The  root  argument specifies the root directory from which to serve static assets. For
more information on the  options  argument, see express.static.
For example, use the following code to serve images, CSS files, and JavaScript files in
a directory named  public :

app.use(express.static('public'))

Now, you can load the files that are in the  public  directory:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

Express looks up the files relative to the static directory, so the name of the static
directory is not part of the URL.
To use multiple static assets directories, call the  express.static  middleware function
multiple times:

FS QB 24
app.use(express.static('public'))
app.use(express.static('files'))

Express looks up the files in the order in which you set the static directories with
the  express.static  middleware function.

NOTE: For best results, use a reverse proxy cache to improve performance of serving


static assets.
To create a virtual path prefix (where the path does not actually exist in the file system)
for files that are served by the  express.static  function, specify a mount path for the
static directory, as shown below:

app.use('/static', express.static('public'))

Now, you can load the files that are in the  public  directory from the  /static  path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

However, the path that you provide to the  express.static  function is relative to the
directory from where you launch your  node  process. If you run the express app from
another directory, it’s safer to use the absolute path of the directory that you want to
serve:

const path = require('path')


app.use('/static', express.static(path.join(__dirname, 'public')))

23.Explain any four modules in Node JS.

FS QB 25
The Built-in HTTP Module
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over
the Hyper Text Transfer Protocol (HTTP).

To include the HTTP module, use the  require()  method:

var http = require('http');

Node.js as a File Server


The Node.js file system module allows you to work with the file system on your
computer.
To include the File System module, use the  require()  method:

var fs = require('fs');

Common use for the File System module:

Read files

Create files

Update files

Delete files

Rename files

The Built-in URL Module


The URL module splits up a web address into readable parts.
To include the URL module, use the  require()  method:

var url = require('url');

FS QB 26
Parse an address with the  url.parse()  method, and it will return a URL object with each
part of the address as properties

Events Module
Node.js has a built-in module, called "Events", where you can create-, fire-, and listen
for- your own events.
To include the built-in Events module use the  require()  method. In addition, all event
properties and methods are an instance of an EventEmitter object. To be able to access
these properties and methods, create an EventEmitter object:

var events = require('events');
var eventEmitter = new events.EventEmitter();

24.Write a node.js server code to integrate with MySQL database


and do the
following operations.
a. Create a database of your own and insert the given into the table.
b. Fetch the record based
- Joining the tables
- Search criteria
- Recent data order
- Limit first 5 record

const express = require("express");


const app = express();
const mysql = require('mysql');

const connection = mysql.createConnection({


host : 'localhost',
user : 'username',

FS QB 27
password : 'password',
database : 'databasename'
});

connection.connect((err) => {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255), createdDate DA
TETIME DEFAULT NOW())";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});

app.get("/insert",(req,res) => {
var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});

app.get("/fetch",(req,res) => {
connection.query('SELECT * from users LIMIT 5 ORDER BY createdDate', (err, rows) => {
if(err) throw err;
console.log('The data from users table are: \n', rows);
res.send(rows);
});
});

app.listen(3000, () => {
console.log('Server is running at port 3000');
});

25. Write a node JS server code to integrate with NOSQL database and do the
following operation:
a). Create a database of your own and insert the given data into the table.

FS QB 28
b). Fetch the record by joining the table
- Search criteria
- Recent data order
- Limit first 5 records

1) What is Nodejs and how to install it.


Node.js is an open source, cross-platform runtime environment and library that is used
for running web applications outside the client’s browser.
It is used for server-side programming, and primarily deployed for non-blocking, event-
driven servers, such as traditional web sites and back-end API services, but was
originally designed with real-time, push-based architectures in m mind.
Installation:

Download node js from official website according to your system

Install node js

Install necessary tools while installing node.

Create a file named filename.js

Set up some javascript code

Run the command node filename.js to see the output in the terminal .

Install express:

In an existing node js project

Open Terminal and execute the command :

npm i express

2) What is MongoDB?

FS QB 29
MongoDB is a document-oriented NoSQL database used for high volume data
storage. Instead of using tables and rows as in the traditional relational databases,
MongoDB makes use of collections and documents. Documents consist of key-
value pairs which are the basic unit of data in MongoDB. Collections contain sets of
documents and function which are the equivalent of relational database tables.

MongoDB stores data in flexible, JSON-like documents, meaning fields can vary
from document to document and data structure can be changed over time

3) What is MongoDB Atlas?


MongoDB Atlas is a fully-managed cloud database that handles all the complexity of
deploying, managing, and healing your deployments on the cloud service provider
of your choice (AWS , Azure, and GCP). MongoDB Atlas is the best way to deploy,
run, and scale MongoDB in the cloud.

4) Steps to set up  MongoDB Atlas.


Create a MongoDB Cloud account.

Create a MongoDB Atlas cluster.

Configure network access and create a cluster user.

Connect to the cluster.

5) How to connect mongodb Atlas ?


Get the connection string from MongoDB Atlas

Whitelist your IP address

Connect to Studio 3T

FS QB 30
Import data in JSON, CSV, BSON/mongodump or SQL

Explore MongoDB data

6) Set up a database connection with Mongodb.


Create the dotenv file and save your private information like mongo url connection
string and specified port.

Paste your Mongo url in an env file with specified username and password.

Create a database schema model in a separate file to store data in the collections in
the mongodb

Initialise Mongoose which helps to connect mongodb to our application

Make a function in the database file and setup general properties and if error occurs
display it in the console

Sample database file:

FS QB 31
7) Steps to Set port in Database connection for application.
Initialise dotenv module .

Set up path for env file

Make a variable PORT and set up a custom port and default port for running our
application.

Sample file:
const dotenv = require('dotenv');
dotenv.config( { path : 'config.env'} )
const PORT = process.env.PORT || 8080

8) How to set up Database Schema ?


Create a Separate file for database schema

Initialise mongoose module from node js.

Create a variable and store the collections and type of documents.

Create a database name and connect to mongoose database schema.

Export the database

Sample file:

FS QB 32
9) Indexing :
MongoDB uses indexing in order to make the query processing more efficient. If there is
no indexing, then the MongoDB must scan every document in the collection and retrieve
only those documents that match the query. Indexes are special data structures that
store some information related to the documents such that it becomes easy for
MongoDB to find the right data file. The indexes are ordered by the value of the field
specified in the index.
Creating an Index :
MongoDB provides a method called createIndex() that allows users to create an index.
Syntax –
db.COLLECTION_NAME.createIndex({KEY:1})

FS QB 33
Pagination :
MongoDB pagination provides an efficient way to model the data which makes the
paging fast and efficient, in MongoDB we can explore a large number of data quickly
and easily. The most important use of paging implementation is it used the skip, limit,
and sort in database level, but limit and skip have some problems to use in database
level. The pagination is nothing but the retrieve next page by using the previous page.
To faster access data, we can create the index on the collections field in MongoDB.

Syntax:
Below is the syntax of MongoDB pagination.
1) MongoDB pagination by using limit method
db.collection_name.find () .limit (number);

2) MongoDB pagination by using skip method


db.collection_name.find () .skip (number);

3) MongoDB pagination using the ID field


db.collection_name.find ( {'_id': { 'Projection_operator': field_name } } )

4) MongoDB pagination using slice operator


db.collection_name.find ( { }, { field_name: {$slice: [number1, number2] } } )

5) MongoDB pagination using ranged queries –


db.collection_name.find () .min ( { _id:0 } ).max ( { _id:3 } )

6) MongoDB pagination using create an index


db.collection_name.createIndex ( {field_name: -1} )

10) Aggregation :
In MongoDB, aggregation operations process the data records/documents and return
computed results. It collects values from various documents and groups them together
and then performs different types of operations on that grouped data like sum, average,
minimum, maximum, etc to return a computed result. It is similar to the aggregate
function of SQL.
Syntax:
Let us view the general syntax of the MongoDB aggregate() method written as follows:
Db.NAME_OF_COLLECTION.aggregate(AGGREGATE_OPERATION);

FS QB 34
MongoDB provides three ways to perform aggregation

Aggregation pipeline

Map-reduce function

Single-purpose aggregation

Aggregation Pipeline
:

MAP-REDUCE FUNCTION:

FS QB 35
SINGLE PURPOSE AGGREGATION:

DISTINCT:

FS QB 36
COUNT:

GROUP:

FS QB 37
11)Node.js Send an Email.
The Nodemailer module makes it easy to send emails from your computer.

The Nodemailer module can be downloaded and installed using npm:

C:\Users\Your Name>npm install nodemailer

Use the username and password from your selected email provider to send an
email.

Code:

12) Node.js Upload Files.


Install the Formidable module from the node js by using the command npm install
formidable.

FS QB 38
Create a Node.js file that writes an HTML form, with an upload field.

Include the Formidable module to be able to parse the uploaded file once it reaches
the server.

When the file is uploaded and parsed, it gets placed on a temporary folder on your
computer.

The path to this directory can be found in the "files" object, passed as the third
argument in the parse() method's callback function.

Sample code:

13) Projection :
Projection allows you to select only the necessary data rather than selecting whole data
from the document. For example, a document contains 5 fields, i.e.,

FS QB 39
{
name: "Roma",
age: 30,
branch: EEE,
department: "HR",
salary: 20000
}

But we only want to display the name and the age of the employee rather than
displaying whole details. Now, here we use projection to display the name and age of
the employee.
One can use projection with the db.collection.find() method. In this method, the second
parameter is the projection parameter, which is used to specify which fields are returned
in the matching documents.
Syntax:
db.collection.find({}, {field1: value2, field2: value2, ..})

If the value of the field is set to 1 or true, then it means the field will be included in
the return document.

If the value of the field is set to 0 or false, then it means the field will not be included
in the return document.

14) What is Replication and Sharding


Replication is the method of duplication of data across multiple servers. For example,
we have an application and it reads and writes data to a database and says this server
A has a name and balance which will be copied/replicate to two other servers in two
different locations.

FS QB 40
By doing this, will get redundancy and increase data availability with multiple copies of
data on different database servers. So, it will increase the performance of reading
scaling. The set of servers that maintain the same copy of data is known as replica
servers or MongoDB instances.
Sharding is a method for allocating data across multiple machines. MongoDB used
sharding to help deployment with very big data sets and large throughput the operation.
By sharding, you combine more devices to carry data extension and the needs of read
and write operations.

15)  MongoDB CRUD Operation


Create :

Create or insert operations add new documents to a collection. If the collection does not
currently exist, insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:

FS QB 41
db.collection.insertOne() - It is used to insert a single document in the collection.

db.collection.insertMany() It is used to insert multiple documents in the


collection.

Read :

Read operations retrieve documents from a collection; i.e. query a collection for
documents. MongoDB provides the following methods to read documents from a
collection:

MongoDB provides the following methods to retrieve documents into a collection:

db.collection.find() - It is used to retrieve all documents that match the condition


in the collection.

db.collection.findOne() It is used to retrieve one document that matches the


condition in the collection.

Update :

Update operations modify existing documents in a collection. MongoDB provides the


following methods to update documents of a collection

db.collection.updateOne()  It is used to update a single document in the


collection that satisfies the given criteria.

db.collection.updateMany() It is used to update multiple documents in the


collection that satisfy the given criteria.

FS QB 42
db.collection.replaceOne() It is used to replace single document in the
collection that satisfy the given criteria.

Delete :

Delete operations remove documents from a collection. MongoDB provides the


following methods to delete documents of a collection:

db.collection.deleteOne() It is used to delete a single document from the


collection that satisfies the given criteria.

db.collection.deleteMany() It is used to delete multiple documents from the


collection that satisfy the given criteria.

FS QB 43
16. How to Download & Install MongoDB on Windows
You can install MongoDB using two different methods one is using msi and another is
using zip. Here, we will discuss how to install MongoDB using msi, so you need to
follow each step carefully:
Step 1: Go to MongoDB Download Center to download MongoDB Community Server.

Here, You can select any version, Windows, and package according to your
requirement.
Step 2: When the download is complete open the msi file and click the next button in the
startup screen:
Step 3: Now accept the End-User License Agreement and click the next button:
Step 4: Now select the complete option to install all the program features. Here, if you
can want to install only selected program features and want to select the location of the
installation, then use the Custom option:
Step 5: Select “Run service as Network Service user” and copy the path of the data
directory. Click Next:
Step 6: Click the Install button to start the installation process:
Step 7: After clicking on the install button installation of MongoDB begins:
Step 8: Now click the Finish button to complete the installation process:
Step 9: Now we go to the location where MongoDB installed in step 5 in your system
and copy the bin path:
Step 10: Now, to create an environment variable open system properties <<
Environment Variable << System variable << path << Edit Environment variable and
paste the copied link to your environment system and click Ok:
Step 11: After setting the environment variable, we will run the MongoDB server, i.e.
mongod.  So, open the command prompt and run the following command:
mongod
The MongoDB server(i.e., mongod) will run successfully.

FS QB 44
17) How to create a backup in MongoDB?
To create backup of database in MongoDB, you should use mongodump command.
This command will dump the entire data of your server into the dump directory. There
are many options available by which you can limit the amount of data or create backup
of your remote server.The basic syntax of mongodump command is as follows −

>mongodump
To restore backup data MongoDB's mongorestore command is used. This command
restores all of the data from the backup directory.
Syntax
The basic syntax of mongorestore command is −

>mongorestore

18)What is a collection in MongoDB?


A collection is a grouping of MongoDB documents. Documents within a collection can
have different fields. A collection is the equivalent of a table in a relational database
system. A collection exists within a single database.

19)What are documents in MongoDB?


MongoDB Document is an entity in which zero or more ordered field-value pairs are
stored. In comparison to Relational Databases, it is analogous to a record or row in
table. Document in MongoDB follows BSON Specifications. BSON is binary encoded
serialization of JSON-like documents.

20) Explain sort and limit in MongoDB:

FS QB 45
Use the sort() method to sort the result in ascending or descending order. This method
takes one parameter, an object defining the sorting order.
db.collection("customers").find().sort({price: 1})

In this example the customers' documents are sorted based on the price field in
ascending order.

Use the value 1 in the sort object to sort ascending.

Use the value -1 in the sort object to sort descending.

The limit() method takes one parameter, a number defining how many documents to
return.
db.collection("customers").find().limit(5)0

21)How would you connect mongosh for deployment?


Run mongosh without any command-line options to connect to a MongoDB instance
running on your localhost with default port 27017
To specify a port to connect to on localhost, you can use:

To connect to a MongoDB instance running on localhost with a non-default port


28015:

The command-line option --port.

EXAMPLE
To connect to a MongoDB instance running on localhost with a non-default port 28015:
mongosh "mongodb://localhost:28015”
mongosh --host mongodb0.example.com --port 28015

FS QB 46
22)List  five commonly used commands in mongosh:
show databases,
show collections (of current database),
use <db-name> (to switch to a database),
version() (for shell version),
quit and
exit.

23)Methods used in Database class and collection class:


The DataBase class has many methods. View them with the command db.help()

getMongo() (get current connection),

getCollectionNames(),

createCollection(),

dropDatabase(), and

stats().

The Collection class has many methods.


View them with the command db.coll.help().
Here are some useful methods:

insert(),

find(),

update(),

deleteOne(),

FS QB 47
aggregate(),

count(),

distinct(),

remove(),

createIndex(),

dropIndex(), and

stats()

24)What are three groups of update operators?


Field Update: Operators include $currentDate (Date or Timestamp),

$inc (increment),

$min (updates only if it's less than current field value),

$max (updates only if it exceeds current field value),

$mul, $rename, $set, $setOnInsert (only if update results in an insert),

and $unset.

Array Update: Operators include $, $[], $[<identifier>],

$addToSet, $pop (-1 to remove first item, 1 to remove last item),

$pull (removes items based on a query condition),

$push (append to array),

and $pullAll (removes items based on a list of values).

Operator modifiers include $each, $position, $slice and $sort.

Bitwise Update: The only operator is $bit.

FS QB 48
It supports AND, OR and XOR updates of integers.

25)How  sql differs from mql?


SQL's (tables, rows, columns) map to MongoDB’s (collections, documents, fields).

SQL's GROUP BY aggregations are implemented via aggregation pipelines in


MongoDB.

Many other features such as primary keys and transactions are equivalent though
not the same.

In SQL, we can drop or add columns to a table. Since MongoDB is schema-less,


these operations are not important.

However, it's possible to add or drop fields using the method updateMany()

26.What are NoSQL databases? What are the different types of


NoSQL databases?
A NoSQL database provides a mechanism for storage and retrieval of data that is
modeled in means other than the tabular relations used in relational databases (like
SQL, Oracle, etc.).
Types of NoSQL databases:

Document Oriented

Key Value

Graph

Column Oriented

27.What kind of NoSQL database MongoDB is?

FS QB 49
MongoDB is a document oriented database. It stores data in the form of BSON structure
based documents. These documents are stored in a collection.

28.Which are the most important features of MongoDB?


∆ Flexible data model in form of documents
∆ Agile and highly scalable database
∆ Faster than traditional databases
∆ Expressive query language

29.How is MongoDB better than other SQL databases?


MongoDB allows a highly flexible and scalable document structure. For e.g. one data
document in MongoDB can have five columns and the other one in the same collection
can have ten columns. Also, MongoDB database are faster as compared to SQL
databases due to efficient indexing and storage techniques.

30.How can you achieve primary key - foreign key relationships in


MongoDB?
By default MongoDB does not support such primary key - foreign key relationships.
However, we can achieve this concept by embedding one document inside another. Foe
e.g. an address document can be embedded inside customer document.

31.How can you achieve transaction and locking in MongoDB?


To achieve concepts of transaction and locking in MongoDB, we can use the nesting of
documents, also called embedded documents. MongoDB supports atomic operations
within a single document.

FS QB 50
32.What is Replication in MongoDB? Explain.
Replication is the process of synchronizing data across multiple servers. Replication
provides redundancy and increases data availability. With multiple copies of data on
different database servers, replication protects a database from the loss of a single
server. Replication also allows you to recover from hardware failure and service
interruptions.

33.What are some of the advantages of MongoDB?


Some advantages of MongoDB are as follows:

MongoDB supports field, range-based, string pattern matching type queries. for
searching the data in the database

MongoDB support primary and secondary index on any fields

MongoDB basically uses JavaScript objects in place of procedures

MongoDB uses a dynamic database schema

MongoDB is very easy to scale up or down

MongoDB has inbuilt support for data partitioning (Sharding).

34.Why MongoDB is known as best NoSQL database?


MongoDB is the best NoSQL database because, it is:
Document Oriented
Rich Query language
High Performance
Highly Available

FS QB 51
Explain step-by-step procedure to connect MongoDB database to
Express server.
require("dotenv").config(); // environment variable

// require packages

const express = require("express");

const mongoose = require("mongoose");

// initialise express

const app = express();

//  mondodb connect

mongoose

.connect(

process.env.MONGODB_URI,

{useNewUrlParser: true, useUnifiedTopology: true}

.then(() => console.log("MongoDB connected"))

.catch(err => console.log(err));

// create a schema

const studentSchema = new mongoose.Schema({

roll_no: Number,

name: String,

year: Number,

subjects: [String]

});

// create a model with studentSchema

const Student = mongoose.model('Student', studentSchema);

// Create a new document

const stud = new Student({

FS QB 52
roll_no: 1001,

name: 'Madison Hyde',

year: 3,

subjects: ['DBMS', 'OS', 'Graph Theory', 'Internet Programming']

});

// Add the document to Collections

stud.save().then(() => console.log("One entry added"), (err) => console.log(err));

// Save method can also be written as:

// stud.save((err, result) => {

//     if(err) console.log(err);

//     else console.log("entry added");

// });

// get documents

app.get('/', (req, res) => {

Student.find({}, (err, found) => {

if (!err) {

res.send(found);

} else {

console.log(err);

res.send("Some error occured!")

});

});

// Server listen

app.listen(3000, () => console.log("Server listening to port 3000"));

FS QB 53
How do you start working on a specific MongoDB Database
through mongo shell?
Local MongoDB Instance on a Non-default Port
To explicitly specify the port, include the --port command-line option. For example, to
connect to a MongoDB instance running on localhost with a non-default port 28015:
mongo --port 28015

MongoDB Instance on a Remote Host .To explicitly specify the hostname and/or port,
You can specify a connection string. For example, to connect to a MongoDB instance
running on a remote host machine:
mongo "mongodb://mongodb0.example.com:28015"

You can use the command-line option --host <host>:<port>.


For example, to connect to a MongoDB instance running on a remote host machine:
mongo --host mongodb0.example.com:28015

What is the command syntax that tells you whether you are on the
master server or not? And how many master does MongoDB
allow?
Command syntax Db.isMaster() will tell you whether you are on the master server or
not. MongoDB allows only one master server.

Is there something like primary key in MongoDB ?


In MongoDB, _id field as the primary key for the collection so that each document can
be uniquely identified in the collection. The _id field contains a unique ObjectID value.
When you query the documents in a collection, you can see the ObjectId for each
document in the collection.

FS QB 54
Write a program to connect a MongoDB database to Node.js?
Approach:-

First, initialize the node.js project in the particular folder in your machine.

install the node modules in the project folder

After this create a connection to the database

Step 1: Create a NodeJS Project and initialize it using the following command:
npm init
Step 2: Install the node modules using the following command:
npm i express mongodb mongoose cors
File Structure: Our file structure will look like the following:

project folder structure

index.js

// To connect with your mongoDB database


const mongoose = require("mongoose");
// Connecting to database
mongoose.connect(
"mongodb://localhost:27017/",
{
dbName: "yourDB-name",
useNewUrlParser: true,

FS QB 55
useUnifiedTopology: true,
},
(err) =>
err ? console.log(err) : console.log("Connected to yourDB-name database")
);
const express = require("express");
const app = express();
const cors = require("cors");
console.log("App listen at port 5000");

Run index.js file using below command:


nodemon index.js

What is Express JS?


Express.js is a small framework that works on top of Node.js web server functionality to
simplify its APIs and add helpful new features. It makes it easier to organize your
application’s functionality with middleware and routing. It adds helpful utilities to Node.js
HTTP objects and facilitates the rendering of dynamic HTTP objects.

Why is MongoDB, a NoSQL Database ?


Like other NoSQL databases, MongoDB doesn't require predefined schemas. It stores
any type of data. This gives users the flexibility to create any number of fields in a
document, making it easier to scale MongoDB databases compared to relational
databases.

Is MongoDB fault tolerant ?


Fault tolerance for a replica set is the number of members that can become
unavailable and still leave enough members in the set to elect a primary. In other
words, it is the difference between the number of members in the set and the majority of
voting members needed to elect a primary.

FS QB 56
Is Express.js front-end or backend framework?
js, or simply Express, is a back end web application framework for Node. js, released as
free and open-source software under the MIT License. It is designed for building web
applications and APIs. It has been called the de facto standard server framework for
Node.

Which database is more popularly used with Node.js?


Node. js supports all kinds of databases no matter if it is a relational database or
NoSQL database. However, NoSQL databases like MongoDb are the best fit with
Node.

Write the step-by-step procedure to Install MongoDB on Windows.


Step 1 — Download the MongoDB MSI Installer Package. Head over here and
download the current version of MongoDB. ...
Step 2 — Install MongoDB with the Installation Wizard. A. ...
Step 3— Create the Data Folders to Store our Databases. A. ...
Step 4 — Setup Alias Shortcuts for Mongo and Mongod. ...
Step 5 — Verify That Setup was Successful.

Differentiate between Express.js and Node.js.


Node.js is a platform for building the i/o applications which are server-side event-driven
and made using JavaScript.

FS QB 57
Express.js is a framework based on Node.js for which is used for building web-
application using approaches and principles of Node.js.event-driven.

Write the step-by-step procedure to Install MongoDB on Ubuntu.W


Step 1 — Installing MongoDB
Ubuntu’s official package repositories include a stable version of MongoDB. However,
as of this writing, the version of MongoDB available from the default Ubuntu repositories
is 3.6, while the latest stable release is 4.4.
To start, import the public GPG key for the latest stable version of MongoDB by running
the following command. If you intend to use a version of MongoDB other than 4.4, be
sure to change 4.4 in the URL portion of this command to align with the version you
want to install:

FS QB 58
curl -fsSL https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

cURL is a command line tool available on many operating systems used to transfer
data. It reads whatever data is stored at the URL passed to it and prints the content to
the system’s output. In the following example, cURL prints the content of the GPG key
file and then pipes it into the following sudo apt-key add - command, thereby adding the
GPG key to your list of trusted keys.
This command will return OK if the key was added successfully:
Output
OK
At this point, your APT installation still doesn’t know where to find the mongodb-org
package you need to install the latest version of MongoDB.
Run the following command, which creates a file in the sources.list.d directory named
mongodb-org-4.4.list. The only content in this file is a single line reading deb [
arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4
multiverse:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4
multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

This single line tells APT everything it needs to know about what the source is and
where to find it:
After running this command, update your server’s local package index so APT knows
where to find the mongodb-org package:
sudo apt update

Following that, you can install MongoDB:


sudo apt install mongodb-org

When prompted, press Y and then ENTER to confirm that you want to install the
package.

When the command finishes, MongoDB will be installed on your system. However it
isn’t yet ready to use. Next, you’ll start MongoDB and confirm that it’s working correctly.

FS QB 59
What is Middleware in Express.js? What are the different types of
Middleware?
Middleware functions are functions that have access to the request object (req), the
response object (res), and the next middleware function in the application’s request-
response cycle. The next middleware function is commonly denoted by a variable
named next.
Middleware functions can perform the following tasks:
Execute any code.
Make changes to the request and the response objects.
End the request-response cycle.
Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must
call next() to pass control to the next middleware function. Otherwise, the request
will be left hanging.

An Express application can use the following types of middleware:

Application-level middleware

Router-level middleware

Error-handling middleware

Built-in middleware

Third-party middleware

Application-level middleware
Bind application-level middleware to an instance of the app object by using the
app.use() and app.METHOD() functions, where METHOD is the HTTP method of the
request that the middleware function handles (such as GET, PUT, or POST) in
lowercase.
const express = require('express')
const app = express()

FS QB 60
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})

Router-level middleware
Router-level middleware works in the same way as application-level middleware, except
it is bound to an instance of express.Router().
const router = express.Router()

Error-handling middleware

Error-handling middleware always takes four arguments. You must provide four
arguments to identify it as an error-handling middleware function. Even if you don’t need
to use the next object, you must specify it to maintain the signature. Otherwise, the next
object will be interpreted as regular middleware and will fail to handle errors.

Built-in middleware
Starting with version 4.x, Express no longer depends on Connect. The middleware
functions that were previously included with Express are now in separate modules; see
the list of middleware functions.

Express has the following built-in middleware functions:


express.static serves static assets such as HTML files, images, and so on.
express.json parses incoming requests with JSON payloads

Third-party middleware
Use third-party middleware to add functionality to Express apps.
Install the Node.js module for the required functionality, then load it in your app at the
application level or at the router level.

FS QB 61
The following example illustrates installing and loading the cookie-parsing middleware
function cookie-parser.

Explain in detail about how to Create Database & Collection in


MongoDB.
1. To access the MongoDB shell, open a terminal window, and run the following
command:
mongo
You are now in the MongoDB shell and can start issuing database commands.
2. Start by issuing a use command. The use command is typically used to switch to a
specific database. However, MongoDB creates a new database if one does not exist.
use example_db

3. The system immediately responds and switches to your new database.


example of the Use command creating a new database in mongodb
You are currently using your newly created database named example_db.

How to List Databases in MongoDB


1. Verify the name of the current database by using the db command:
use db

Your system should display example_db (or the name you specified).
example of using the db command checking database name
2. List all the databases on your system with the show dbs command:
show dbs

You may notice that your new database is not listed.


show dbs command Listing of MongoDB databases

FS QB 62
The newly created database is empty – you’ll need to insert data for it to display in this
list
Add MongoDB Collection with insert() Command
A collection in MongoDB is much like a table in other database applications.
The following command creates a record and inserts it into a newly created collection. A
record is a document with field names and values. As with a new database, if this
record does not exist, MongoDB creates it:
db.Sample.insert({"SampleValue1" : 255, "SampleValue2" : "randomStringOfText"})

Let’s take a closer look at the syntax of the command to understand how the record and
collection are created.
db.Sample.insert – This is the insert command. In this example, the name Sample
represents the name of the document you’re inserting data into. If the document does
not already exist, MongoDB automatically creates it.
({  }) – The set of brackets encloses the data you are entering. Note that there’s a set of
close-brackets at the end.
"SampleValue1" : 255, "SampleValue2" :  "randomStringOfText" – Represents the
format of the data we are entering into the record.
After you execute the command, you see the following response:
WriteResult({ "nInserted" : 1})
This response confirms that the system automatically created a collection and the
record was inserted into said collection.
MongoDB confirms that you have successfully inserted data to a new collection
If you list the existing databases with the show dbs command, you’ll notice that the
example_db database is now on the list.

Write the steps for setting up an Express JS application?


Following are the steps accustomed for An Express JS application:

A folder with a constant name because the project name is made.

FS QB 63
A file named package.json is made within the folder created.

“npm install” command is run on the electronic communication. It installs all the
libraries gift in package.json.

“npm i express —save” for installing express package

and to import package use “ const express = require(”express”);” in your file.

A file named server.js is made.

“Router” file is made within the package that consists of a folder named index.js.

“App” is made within the package that has the index.html file.

Write the step by step procedure to insert () and delete ()


Document with an example in MongoDB.
Insert a Single Document
db.collection.insertOne() inserts a single document into a collection.
The following example inserts a new document into the inventory collection. If the
document does not specify an _id field, MongoDB adds the _id field with an ObjectId
value to the new document. See Insert Behavior.
db.inventory.insertOne(

{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }

MongoDB Shell
You can run the operation in the web shell below:
insertOne() returns a document that includes the newly inserted document's _id field
value. For an example of a return document, see db.collection.insertOne() reference.
To retrieve the document that you just inserted, query the collection:
db.inventory.find( { item: "canvas" } )

MongoDB Shell
Insert Multiple Documents

FS QB 64
➤ Use the Select your language drop-down menu in the upper-right to set the language
of the examples on this page.
New in version 3.2.
db.collection.insertMany() can insert multiple documents into a collection. Pass an array
of documents to the method.
The following example inserts three new documents into the inventory collection. If the
documents do not specify an _id field, MongoDB adds the _id field with an ObjectId
value to each document. See Insert Behavior.
db.inventory.insertMany([

{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" }},

{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },

{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom:"cm"}}

])

Delete Documents
➤ Use the Select your language drop-down menu in the upper-right to set the language
of the following examples.

This page uses the following mongosh methods:


db.collection.deleteMany()

db.collection.deleteOne()

The examples on this page use the inventory collection. To populate the inventory
collection, run the following:
db.inventory.insertMany( [

{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },

{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },

{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },

{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },

{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },

] );

Write a program to Integrate MongoDB with Your Node


Application.

FS QB 65
Connect to your database from a Node.js application
Import MongoClient

The MongoDB module exports MongoClient, and that’s what we’ll use to connect to a
MongoDB database. We can use an instance of MongoClient to connect to a cluster,
access the database in that cluster, and close the connection to that cluster.
const {MongoClient} = require('mongodb');

Create our main function


Let’s create an asynchronous function named main() where we will connect to our
MongoDB cluster, call functions that query our database, and disconnect from our
cluster.
async function main() {

// we'll add code here soon

const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?


retryWrites=true&w=majority";

Now that we have our URI, we can create an instance of MongoClient.


const client = new MongoClient(uri);

Now we're ready to use MongoClient to connect to our cluster. client.connect() will
return a promise. We will use the await keyword when we call client.connect() to
indicate that we should block further execution until that operation has completed.
await client.connect();

Now we are ready to interact with our database. Let's build a function that prints the
names of the databases in this cluster. It's often useful to contain this logic in well
named functions in order to improve the readability of your codebase. Throughout this
series, we'll create new functions similar to the function we're creating here as we learn
how to write different types of queries. For now, let's call a function named
listDatabases().
await listDatabases(client);

Let’s wrap our calls to functions that interact with the database in a try/catch statement
so that we handle any unexpected errors.
try {

await client.connect();

await listDatabases(client);

} catch (e) {

FS QB 66
console.error(e);

We want to be sure we close the connection to our cluster, so we’ll end our try/catch
with a finally statement.
finally {

await client.close();

Once we have our main() function written, we need to call it. Let’s send the errors to the
console.
main().catch(console.error);

Putting it all together, our main() function and our call to it will look something like the
following.
async function main(){

const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?


retryWrites=true&w=majority";

const client = new MongoClient(uri);

try {

await client.connect();

await listDatabases(client);

} catch (e) {

console.error(e);

} finally {

await client.close();

main().catch(console.error);

List the databases in our cluster


In the previous section, we referenced the listDatabases() function. Let’s implement it!
This function will retrieve a list of databases in our cluster and print the results in the
console.
async function listDatabases(client){

databasesList = await client.db().admin().listDatabases();

console.log("Databases:");

databasesList.databases.forEach(db => console.log(` - ${db.name}`));

FS QB 67
};

Save Your File


You’ve been implementing a lot of code. Save your changes, and name your file
something like connection.js. To see a copy of the complete file, visit the nodejs-
quickstart GitHub repo.

Write the step by step procedure to update () Document with an


example in MongoDB.
Step 1) Issue the update command
Step 2) Choose the condition which you want to use to decide which document needs to
be updated. In our example, we want to update the document which has the Employee
id 22.
Step 3) Use the set command to modify the Field Name
Step 4) Choose which Field Name you want to modify and enter the new value
accordingly.
db.Employee.update(
{"Employeeid" : 1},
{$set: { "EmployeeName" : "NewMartin"}});
If the command is executed successfully, the following Output will be shown
Output:
MongoDB Update() Document
The output clearly shows that one record matched the condition and hence the relevant
field value was modified.
Updating Multiple Values
Step 1) Issue the update command
Step 2) Choose the condition which you want to use to decide which document needs to
be updated. In our example, we want the document which has the Employee id of “1” to
be updated.

FS QB 68
Step 3) Choose which Field Name’s you want to modify and enter their new value
accordingly.
db.Employee.update
(
{
Employeeid : 1

},
{
$set :
{
"EmployeeName" : "NewMartin",
"Employeeid" : 22
}
}
)
If the command is executed successfully and if you run the “find” command to search for
the document with Employee id as 22

Explain in detail about various CRUD operations in MongoDB.


Create :
Create or insert operations add new documents to a collection. If the collection does not
currently exist, insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:

db.collection.insertOne() - It is used to insert a single document in the collection.

db.collection.insertMany() It is used to insert multiple documents in the collection.

FS QB 69
Read :
Read operations retrieve documents from a collection; i.e. query a collection for
documents. MongoDB provides the following methods to read documents from a
collection:
MongoDB provides the following methods to retrieve documents into a collection:

db.collection.find() - It is used to retrieve all documents that match the condition in


the collection.

db.collection.findOne() It is used to retrieve one document that matches the


condition in the collection.

Update :
Update operations modify existing documents in a collection. MongoDB provides the
following methods to update documents of a collection

db.collection.updateOne()  It is used to update a single document in the


collection that satisfies the given criteria.

db.collection.updateMany() It is used to update multiple documents in the


collection that satisfy the given criteria.

db.collection.replaceOne() It is used to replace single document in the


collection that satisfy the given criteria.

FS QB 70
Delete :
Delete operations remove documents from a collection. MongoDB provides the
following methods to delete documents of a collection:

db.collection.deleteOne() It is used to delete a single document from the collection


that satisfies the given criteria.

db.collection.deleteMany() It is used to delete multiple documents from the


collection that satisfy the given criteria.

FS QB 71
Explain Error Handling In Express.js Using An Example?
Error Handling
Error Handling refers to how Express catches and processes errors that occur both
synchronously and asynchronously. Express comes with a default error handler so you
don’t need to write your own to get started.
Catching Errors
It’s important to ensure that Express catches all errors that occur while running route
handlers and middleware.
Errors that occur in synchronous code inside route handlers and middleware require
no extra work. If synchronous code throws an error, then Express will catch and process
it. For example:
app.get('/', (req, res) => {

throw new Error('BROKEN') // Express will catch this on its own.

})

For errors returned from asynchronous functions invoked by route handlers and
middleware, you must pass them to the next() function, where Express will catch and
process them. For example:
app.get('/', (req, res, next) => {

fs.readFile('/file-does-not-exist', (err, data) => {

if (err) {

next(err) // Pass errors to Express.

} else {

res.send(data)

})

})

Starting with Express 5, route handlers and middleware that return a Promise will call
next(value) automatically when they reject or throw an error. For example:
app.get('/user/:id', async (req, res, next) => {

const user = await getUserById(req.params.id)

FS QB 72
res.send(user)

})

If getUserById throws an error or rejects, next will be called with either the thrown error
or the rejected value. If no rejected value is provided, next will be called with a default
Error object provided by the Express router.
If you pass anything to the next() function (except the string 'route'), Express regards
the current request as being an error and will skip any remaining non-error handling
routing and middleware functions.
If the callback in a sequence provides no data, only errors, you can simplify this code as
follows:
app.get('/', [

function (req, res, next) {

fs.writeFile('/inaccessible-path', 'data', next)

},

function (req, res) {

res.send('OK')

])

In the above example next is provided as the callback for fs.writeFile, which is called
with or without errors. If there is no error the second handler is executed, otherwise
Express catches and processes the error.

Write step by step procedure about how to install MongoDB in


windows.

A Step-by-Step Guide to MongoDB Installation on Windows


Navigate to the download site
Navigate to the official MongoDB website.
MongoDB Developer and Administrator Course

FS QB 73
Gain in-depth knowledge and become an expertENROLL NOW
Cross-check the Specifications and Download MongoDB
Under the Software section, click on the Community server version.
MongoDB_Installation
Make sure that the specifications to the right of the screen are correct. At the time of
writing, the latest version is 4.4.5. Ensure that the platform is Windows, and the
package is MSI. Go ahead and click on download.
Installation_MongoDB.
MongoDB Installation
You can find the downloaded file in the downloads directory. You can follow the steps
mentioned there and install the software.
MongoDB_Setup
Setup_MongoDB
On completing the installation successfully, you will find the software package in your C
drive. C:\Program Files\MongoDB\Server\4.4\bin.
/MongoDB.
You can see that there are mongo and mongod executable files. The mongod file is the
daemon process that does the background jobs like accessing, retrieving, and updating
the database.
Create an Environment Variable
It’s best practice to create an environment variable for the executable file so that you
don’t have to change the directory structure every time you want to execute the file.
Mongo_EnvironmentVariable
EnvVariable_MongoDB.
MongoDB Developer and Administrator: Free Course
MongoDB Developer & Administrator Basics for FREESTART LEARNING
Execute the Mongo App
After creating an environment path, you can open the command prompt and just type in
mongo and press enter.

FS QB 74
Mongo_Setup.
The mongo server is then generated and is up and running.
Big Data Engineer Master's Program
Master All the Big Data Skill You Need TodayENROLL NOW
Verify the Setup
To verify if it did the setup correctly, type in the command show DBS.
Setup_Mongo

With that, you have successfully installed and set up MongoDB on your Windows
system.
MongoDB_Example
This demo sample has also created a database called mydatabase, with some data
added to it. It has also displayed the same using the find() method

Explain step-by-step procedure to connect MongoDB database to


Express server.
Step 1: Initialise npm on the directory and install the necessary modules. Also, create
the index file. (To get started with express, read this article )
$ npm init
$ touch index.js
$ npm i express mongoose

Step 2: Initialise the express app and make it listen to a port on localhost.
const express = require("express");

const app = express();

app.listen(3000, () => console.log("Server is running"));

Step 3: Require mongoose package


const mongoose = require("mongoose");

Connect to a cluster in MongoDB cloud

FS QB 75
1. Connection code

Provide the MongoDB URI of your cluster to mongoose.connect() ( refer to this article
for creating a free-tier cluster for MongoDB in the cloud)
mongoose.connect(

process.env.MONGODB_URI,

useNewUrlParser: true,

useUnifiedTopology: true

);

process.env.MONGODB_URI — used to get value from environment variable


It is recommended to use an environment variable so that your credentials will not be
exposed when you are uploading your repository online.
dotnev npm package can be used to provide environment variables
$ npm i dotenv
In the index.js file, add the following at the top.
require("dotenv").config();

Create a .env file and provide your credentials there in the provided format (key=value)
MONGODB_URL="your-mongodb-uri-here"

Make sure you included .env file along with node_modules directory in .gitignore.

.gitignore file
2. Define a schema
Let’s create a schema for a new collection.
Schema defines the structure of the document, with all the field names and type.
const studentSchema = new mongoose.Schema({

roll_no: Number,

name: String,

year: Number,

subjects: [String]

});

mongoose.schema() takes in a javascript object.

FS QB 76
Name of the property is the fields for the document
Value for the property represents the type for the particular field.
To make any field required, make required as true.
roll_no: {

type: Number,

required: true

Since we wanted to specify that it is required i.e. to send another information along with
the type of the field, we represent the values that are to be sent in an object.
To know more about the schema types, read the documentation here.
3. Define the model
Let’s create our model by passing in the schema and a name for our model.
const Student = mongoose.model('Student', studentSchema);

studentSchema — the schema we have created just now

‘Student’ — Name for the model, so a collection will be created with a name
‘students’ (plural form of the name with all lowercase)

Now as our model is ready, we can create APIs to get, add, delete, update our
documents within our collection.
Let’s add two documents whenever our app is loaded
const stud = new Student({

roll_no: 1001,

name: 'Madison Hyde',

year: 3,

subjects: ['DBMS', 'OS', 'Graph Theory', 'Internet Programming']

});

stud.save().then(() => console.log("One entry added"));

By sending an object containing the values to our model Student, we can create a new
document and use save() method to save our document to the cloud.
Now, Let's define a get request for the root route which returns all the documents in
Student collection which should return the document we added.
app.get('/', (req, res) => {

FS QB 77
Student.find({}, (err, found) => {

if (!err) {

res.send(found);

console.log(err);

res.send("Some error occured!")

})

});

model.find() finds and returns documents


The first parameter {} — to specify queries to receive documents that match a certain
condition. (Here, we leave it blank to get all the documents)
The second parameter is a callback function, which returns documents found and error
if any occurs.
res.send(found) returns the documents found back as a response
Let’s try running our app!
console
You can see ‘MongoDB connected’ and ‘One entry added’ messages in our console.

In the render function, instead of returning one <div>, try


returning two <div> elements placed one after the other. Explain in
detail about what happens? why, and what’s the solution?

A single line works fine:

render: function () {
return (
<p>{n}</p>

);
}

But not for multiple lines:

FS QB 78
render: function () {
return (
<h3>Item {n}</h3>
<p>Description {n}</p>
)
);
}

It should now be clear that the second snippet doesn't really make sense (you can't
return more than one value in JavaScript). You have to either wrap it in another element
(most likely what you'd want, that way you can also provide a valid  key
 property)
it is possible to return multiple elements by wrapping them within an  Array :

render() {
return [
<div><h3>Item {n}</h3></div>
<div><p>Description {n}</p></div>
];

a new feature called  React Fragments  is introduced which you can use to wrap multiple
elements:

render() {
return (

<React.Fragment key={index}>
<div><h3>Item {n}</h3></div>
<div><p>Description {n}</p></div>
</React.Fragment>
);
}

Ensure you look at the console running npm run watch.

FS QB 79
npm run dev combines all your JavaScript files into a browser-friendly combined file.
npm run watch does the same, but then it stays active and "watches" for updates to
your .js files. If it detects a change, it'll re-build the browser-friendly file so you can just
refresh the page.
The difference between dev and watch is the dev command will compile the code then
exit while the watch command will compile the components then watch the files and
recompile when one of them changes.

How to setup React Environment on your computer to deploy


React application.

So first, it needs to install Nodejs on our system. NPM will be installed with Nodejs. The
current stable version of Node.js can be downloaded and installed from the official
website that is given below.

https://nodejs.org

Download the latest version and install it. Here we can choose the LTS or the latest
version. Because both of the version supports React.
After the installation, check the versions using the below commands.

node -v
npm -v

This will show the installed versions of Node.js and NPM.

After the successful installation of Nodejs and NPM, we can create a new React project
by temporarily installing the create-react-app tool. Execute the below command on the
Command prompt window.

FS QB 80
npx create-react-app awesome-project

Here NPX will temporarily install create-react-app and create a new react project
named awesome-project. Note that the awesome-project is the name I have chosen
for my react project.

So the app we created can run locally on our system with the npm start command.

cd awesome-project
npm start

This will open up the react application in a new tab of our browser with the below URL.

http://localhost:3000

👆 ipdi dhan output irukum pathukonga makkaleh

FS QB 81
You’d have noticed that we did not use NavLinks for the filter links.
Try changing these also to NavLinks. What do you observe when
you navigate between the filters? Can you explain this in detail.

The <NavLink> component is similar to the <Link> component, except that several
props can be specified that help you to conditionally add styling attributes to the
rendered element. It accepts the same set of props as the <Link> component (to,
replace, and innerRef) for navigating to a route, and it includes props to style the
selected route.

<NavLink>

A special version of the  <Link>  that will add styling attributes to the rendered element
when it matches the current URL.

<NavLink to="/about">About</NavLink>

className: string | func


className  can either be a string or a function that returns a string. If the
function  className  is used, the link’s  active  state is passed as a parameter. This is
helpful if you want to exclusively apply a  className  to an inactive link.

<NavLinkto="/faq"className={isActive =>
"nav-link" + (!isActive ? " unselected" : "")
}>
FAQs
</NavLink>

Navigate between two different issues’ edit pages, by changing the


Issue ID in the URL bar, or by creating a bookmark for one of them.

FS QB 82
The two different pages are shown correctly. Compare this with
the Issue List page, where a componentDidUpdate() method was
needed. Explain in detail why this is so

when you navigate using the hyperlinks


for each hard-coded filter, you will find that the list of issues doesn’t change, even
though the browser URL reflects the new query string. But it does work when you
refresh the browser.
The reason is that we are calling loadData() only when the component is mounted.
When there is a change in the query string, the component is not mounted again;
instead,
React reuses the component that’s already mounted.
we need to hook into a method that tells us that the route query string has
changed, so that we can reload the list. The Component Lifecycle guide for React
Router recommends we do it in the lifecycle method componentDidUpdate(), which
gives us a hook whenever any property of the component changes

...
componentDidUpdate(prevProps) {
const oldQuery = prevProps.location.query;
const newQuery = this.props.location.query;
if (oldQuery.status === newQuery.status) {
return;
}
this.loadData();
}
...
IssueList.propTypes = {
location: React.PropTypes.object.isRequired,
};
...

Now, testing will show you that navigating between the filter links indeed reloads the
data.

👆idha padicha onnum puriyathu dhan but ithu dhan answer uuh

FS QB 83
Explain in detail about routing with React routers with the sample
code.
React Router
Routing is a process in which a user is directed to different pages based on their action
or request. ReactJS Router is mainly used for developing Single Page Web
Applications. React Router is used to define multiple routes in the application. When a
user types a specific URL into the browser, and if this URL path matches any 'route'
inside the router file, the user will be redirected to that particular route.

React Router Installation


React contains three different packages for routing. These are:

1. react-router: It provides the core routing components and functions for the React
Router applications.

2. react-router-native: It is used for mobile applications.

3. react-router-dom: It is used for web applications design.

It is not possible to install react-router directly in your application. To use react routing,
first, you need to install react-router-dom modules in your application. The below
command is used to install react router dom.

1. $ npm install react-router-dom --save

Components in React Router


There are two types of router components:

<BrowserRouter>: It is used for handling the dynamic URL.

<HashRouter>: It is used for handling the static request.

Eg:
import  React from 'react';

import  ReactDOM from 'react-dom';

import  { Route, Link, BrowserRouter as Router } from 'react-router-dom'

FS QB 84
import  './index.css';

import  App from './App';

import  About from './about'

import  Contact from './contact'

const  routing = (

<Router>

<div>

<h1>React Router Example</h1>

<Route path="/" component={App} />

<Route path="/about" component={About} />

<Route path="/contact" component={Contact} />

</div>

</Router>

ReactDOM.render(routing, document.getElementById('root'));

Design a JavaScript program to display a message “Hi good


morning to you” when a page is loaded and displays a message
“Thanks for visiting our web page” when a page is unloaded.
<!DOCTYPE html>

<html lang="en">

<head>

<title>Hello World</title>

</head>

<body>

<h1 id="msg-box"></h1>

<script>

const scriptURL =

" https://cdn.jsdelivr.net/npm/react@18.0.0/index.min.js ";

const msgBox = document.getElementById("msg-box");

let script = document.createElement('script');

script.src = scriptURL;

FS QB 85
document.head.append(script);

script.onload = ()=>{

msgBox.textContent = "Hi Good morning to you"

};

script.onerror = ()=>{

msgBox.textContent="Thanks for visiting our webpage";

};

</script>

</body>

</html>

Implement routing for the Adventure Trails application as per the


below requirement. Write the necessary code in the routes/route.js
file.
Route Path : /packages
Success response: Status code: 200
A JSON object with property:
message: "You can now get the requested packages for your request".
Error response: Status code: 404
A JSON object with property:

status: "fail"
message: the error message

const createBook = async (req, res, next) => {


const newBook = new Book(req.body);

try {
const savedBook = await newBook.save();
res.status(200).json(savedBook);
res.send("You can now get the requested packages for your request")
} catch (err) {
next(createError(404, "Cannot create book"));

FS QB 86
}
};

//get books package


const getBook = async (req, res, next) => {
try {
const Book = await Book.findById(req.params.id);
res.status(201).json(Book);
res.send("New booking added for the POST request")
} catch (err) {
next(createError(404, "Cannot get packages"));
}
};

const router = express.Router();

router.post('/',createBook);

router.get('/package/:id',getBook);

Create an online-examination web portal. Prepare the questions of


your choice. The students should enter their name and register
number before answering the questions. The online exam should
contain at least five questions of type multiple choice. The choice
of selection should use radio buttons and for each correct answer
one mark should be awarded. After attempting all questions,
proceed with submit button. After clicking the submit button,
display the result with register number, name of the student and
marks. Design a web portal using JavaScript and HTML forms.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">

FS QB 87
<!-- Coding with nick -->
<title>Quiz App</title>
</head>
<body>

<div class="quiz-container" id="quiz">


<div class="quiz-header">
<h2 id="question">Question Text</h2>
<ul>
<li>
<input type="radio" name="answer" id="a" class="answer">
<label for="a" id="a_text">Answer</label>
</li>
<li>
<input type="radio" name="answer" id="b" class="answer">
<label for="b" id="b_text">Answer</label>
</li>

<li>
<input type="radio" name="answer" id="c" class="answer">
<label for="c" id="c_text">Answer</label>
</li>

<li>
<input type="radio" name="answer" id="d" class="answer">
<label for="d" id="d_text">Answer</label>
</li>

</ul>
</div>

<button id="submit">Submit</button>
</div>

<script src="script.js"></script>

</body>
</html>

const quizData = [
{
question: "Which language runs in a web browser?",
a: "Java",
b: "C",
c: "Python",
d: "javascript",
correct: "d",
},
{
question: "What does CSS stand for?",
a: "Central Style Sheets",

FS QB 88
b: "Cascading Style Sheets",
c: "Cascading Simple Sheets",
d: "Cars SUVs Sailboats",
correct: "b",
},
{
question: "What does HTML stand for?",
a: "Hypertext Markup Language",
b: "Hypertext Markdown Language",
c: "Hyperloop Machine Language",
d: "Helicopters Terminals Motorboats Lamborginis",
correct: "a",
},
{
question: "What year was JavaScript launched?",
a: "1996",
b: "1995",
c: "1994",
d: "none of the above",
correct: "b",
},

];

const quiz = document.getElementById('quiz')


const answerEls = document.querySelectorAll('.answer')
const questionEl = document.getElementById('question')
const a_text = document.getElementById('a_text')
const b_text = document.getElementById('b_text')
const c_text = document.getElementById('c_text')
const d_text = document.getElementById('d_text')
const submitBtn = document.getElementById('submit')

let currentQuiz = 0
let score = 0

loadQuiz()

function loadQuiz() {

deselectAnswers()

const currentQuizData = quizData[currentQuiz]

questionEl.innerText = currentQuizData.question
a_text.innerText = currentQuizData.a
b_text.innerText = currentQuizData.b
c_text.innerText = currentQuizData.c
d_text.innerText = currentQuizData.d
}

function deselectAnswers() {

FS QB 89
answerEls.forEach(answerEl => answerEl.checked = false)
}

function getSelected() {
let answer
answerEls.forEach(answerEl => {
if (answerEl.checked) {
answer = answerEl.id
}
})
return answer
}

submitBtn.addEventListener('click', () => {
const answer = getSelected()
if (answer) {
if (answer === quizData[currentQuiz].correct) {
score++
}

currentQuiz++

if (currentQuiz < quizData.length) {


loadQuiz()
} else {
quiz.innerHTML = `
<h2>You answered ${score}/${quizData.length} questions correctly</h2>

<button onclick="location.reload()">Reload</button>
`
}
}
})

Write the procedure to install Node.js Locally with Node Version


Manager (nvm).

to install  nvm  on your system is to use the official installer script:

VERSION=v0.37.2
curl -o- "https://raw.githubusercontent.com/nvm-sh/nvm/${VERSION}/install.sh" | bash

FS QB 90
Once  nvm
 is installed in your system,

# installs the latest version of Node.js


nvm install node

One great thing about  nvm  is that it allows to specify the Node.js version you want to
use for a given project.
For instance, if you are working on a project that requires you to use Node.js  10.10  you
can do the following (in the root folder of the project):

echo "10.10" > .nvmrc

Then every time you work on that project, you only need to run:

nvm use

Which should print something like this:

Found '/path/to/project/.nvmrc' with version <10.10>


Now using node v10.10.1 (npm v6.7.3)

At this point, you can be sure that you working using the correct Node.js version for your
project.

FS QB 91

You might also like