0% found this document useful (0 votes)
23 views6 pages

Node Js IMP

Uploaded by

gyanchod23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views6 pages

Node Js IMP

Uploaded by

gyanchod23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Q1>What is Node. JS?

Q5List any two methods included under path


Node. js (Node) is an Open Source, cross-platform module of node. JS.
runtime environment for executing JavaScript code. join()=Joins the specified paths into one
Node is used extensively for server-side normalize()=Normalizes the specified path
programming, making it possible for developers to parse()=Formats a path string into a path object
use JavaScript for client-side and server-side code posix=Returns an object containing POSIX specific
without needing to learn an additional language properties and methods

Q2> features node. JS? Q6 which tasks a File System module is used for?
Asynchronous and Event-Driven: The Node.js library’s The File System module is frequently used for the
APIs are all asynchronous (non-blocking) in nature. following purposes: File Reading. File Creation. File
Single-Threaded: Node.js employs a single-threaded Updation.
architecture with event looping, making it very
scalable. Scalable: NodeJs addresses one of the Q7Write a command to add dependency “express”
most pressing concerns in software development: usingNPM. Step 1: Install Node. js on your Windows
scalability. Quick execution of code: Node.js makes machine with its latest version. Step 2: Open a
use of the V8 JavaScript Runtime motor, which is command prompt or PowerShell Window. Step 3: Run
also used by Google Chrome. Cross-platform the command npm install express –g to globally
compatibility: NodeJS may be used on a variety of install Express.
systems, including Windows, Unix, Linux, Mac OS X,
and mobile devices. Q8Write a command to install MYSOL Package by
usinNPM?
Q3> advantages of nodes.JS? oad the existing node_modules tree from disk.
Speed: One of the key benefits of Node.js clone the tree.
development is its speed, which makes it a great fetch the package.json and assorted metadata and
choice for dynamic applications. The runtime add it to the clone.
environment of Node.js is based on an event loop walk the clone and add any missing dependencies.
that handles multiple concurrent requests easily and dependencies will be added as close to the top as is
quickly, allowing you to scale your application with possible.
ease. 2. Productivity: Node.js is a highly productive
platform for developing web applications. It’s a single- Q9>Write down steps to handle http requests while
threaded, event-driven environment, which makes it creating web server using node. JS Step 1: Import
ideal for real-time applications such as chat and the HTTP module const http = require('http'); // Step
video streaming. 3. Error handling: Node.js has a 2: Create the server using the http. createServer()
built-in error-handling mechanism that allows you to method const server = http. createServer((req, res) =>
catch errors at runtime and do something with them.. { // Step 3: Set the response headers res.
4. Cost-effectiveness: There are several benefits to writeHead(200, {'Content-Type': 'text/plain'}); // Step 4:
using Node.js development services, including Send the response body res.
cost-effectiveness. The main reason why companies
choose this technology is because of its cost savings Q5>In which situation node. JS is not recomended to
and time savings. 5. Faster development: Node.js is use? js receives a CPU-bound task: Whenever a heavy
a platform for building fast websites and web apps. request comes to the event loop, Node. js would set
It’s also the most popular platform for building all the CPU available to process it first, and then
microservices, which means you can use it to build answer other requests queued. That results in slow
applications that have many small parts that work processing and overall delay in the event loop, which
together as one system. is why Node. js is not recommended for heavy
computation.
Q4>What is the command to initialize node package Q4>Traditional web server model?If no thread is
manager (NPM)? Write it’s syntax. available in the thread pool at any point of time then
To better illustrate how options are forwarded, here’s the request waits till the next available thread.
a more evolved example showing options passed to Dedicated thread executes a particular request and
both the npm cli and a create package, both does not return to thread pool until it completes the
following commands are equivalent: npm init foo -y – execution and returns a response. In the traditional
registry=<url> -- --hello -a. npm exec -y –registry=<url> - web server model, each request is handled by a
- create-foo –hello -a. dedicated thread from the thread pool. If no thread is
available in the thread pool at any point of time then
the request waits till the next available thread.
Q5>node js process model?
Node. js processes user requests differently when Q8>List any four core modules of node.JS?
compared to a traditional web server model. Node. js In Node.js, Modules are the blocks of encapsulated
runs in a single process and the application code code that communicate with an external application
runs in a single thread and thereby needs less on the basis of their related functionality. Modules
resources than other platforms. A process object is a can be a single file or a collection of multiple
global object that gives information about and files/folders. The reason programmers are heavily
controls the node.js process. As it is global, it can be reliant on modules is because of their reusability as
used in the project without importing it from any well as the ability to break down a complex piece of
module. code into manageable chunks. Modules are of three
types: Core Modules ,local Modules ,Third-party
Modules
Core Modules: Node.js has many built-in modules
that are part of the platform and come with Node.js
installation. These modules can be loaded into the
program by using the required function.
Syntax: const module = require('module_name');
Local Modules: Unlike built-in and external modules,
local modules are created locally in your Node.js
application. Let’s create a simple calculating module
that calculates various operations.Third-party
modules: Third-party modules are modules that are
available online using the Node Package
Manager(NPM). These modules can be installed in
Q6> Explain steps to install node. JS on windows.? the project folder or globally. Some of the popular
The Node can be installed in multiple ways on a third-party modules are Mongoose, express, angular,
computer. The approach used by you depends on the and React.
existing development environment in the system.
There are different package installers for different Q9>module.experts in node. JS?
environments. You can install Node by grabbing a In Node, the `module.exports` is utilized to expose
copy of the source code and compiling the literals, functions, or objects as modules. This
application. Another way of installing Node is by mechanism enables the inclusion of JavaScript files
cloning the GIT repository in all three environments within Node.js applications. The `module` serves as a
and then installing it on the system. Step 1: reference to the current module, and `exports` is an
Downloading the Node.js ‘.msi’ installer the first step object that is made accessible as the module’s public
to install Node.js on Windows is to download the interface. Syntax:
installer. Visit the official Node.js website i.e) module.exports = literal | function | object
https://nodejs.org/en/download/Step-2: Running the Note: Here the assigned value (literal | function |
Node.js installer.Step 3: Verify that Node.js was object) is directly exposed as a module and can be
properly installed or not.Step 4: Updating the Local used directly. Syntax:
npm version. module.exports.variable = literal | function | object

Q7>What is REPL? Q9>Write any two functions of Buffer used in node.


The Node. js Read-Eval-Print-Loop (REPL) is an JS.
interactive shell that processes Node. js expressions. Buffers in Node.js: The Buffer class in Node.js is used
The shell reads JavaScript code the user enters, to perform operations on raw binary data. Generally,
evaluates the result of interpreting the line of code, Buffer refers to the particular memory location in
prints the result to the user, and loops until the user memory. Buffer and array have some similarities, but
signals to quit. The REPL is bundled with every Node. the difference is array can be any type, and it can be
REPL is an acronym for Read, Evaluate, Print, and resizable. Buffers only deal with binary data, and it
Loop. Developers use REPL Python to communicate can not be resizable. Each integer in a buffer
with the Python Interpreter. In contrast to running a represents a byte. console.log() function is used to
Python file, you can input commands in the REPL and print the Buffer instance.
see the results displayed immediately.
1>Buffer.alloc(size)=It creates a buffer and allocates Step 2: Go to the project directory where you want to
size to it. install the local module and enter this command.
2>Buffer.from(initialization)=It initializes the buffer npm link package-name.
with given data. Q14> install global package?
3>Buffer.write(data)=It writes the data on the buffer. Installing “globally” means the package is installed in
the npm root directory. Typically, globally installed
Q10>Anonymous function with an example.? packages are executables, so npm usually creates a
It is a function that does not have any name shortcut/shim so the package is available on your
associated with it. Normally we use the function PATH (i.e. you can run the command anywhere)
keyword before the function name to define a
function in JavaScript, however, in anonymous Q15>web server?
functions in JavaScript, we use only the function The word web server compromises of hardware of
keyword without the function name. software or both of them working simultaneously. It
An anonymous function is not accessible after its has two parts which is hardware and software part.
initial creation, it can only be accessed by a variable it The term web server can refer to hardware or
is stored in as a function as a value. An anonymous software, or both of them working together. On the
function can also have multiple arguments, but only hardware side, a web server is a computer that stores
one expression. web server software and a website's component files
(for example, HTML documents, images, CSS
Q11>Write a short note on NPM.? stylesheets, and JavaScript files).
NPM (Node Package Manager) is the default
package manager for Node and is written entirely in Q16> creating web server in node js?
JavaScript. Developed by Isaac Z. Schlueter, it was HTTP and HTTPS, these two inbuilt modules are used
initially released in January 12, 2010. NPM manages to create a simple server. The HTTPS module
all the packages and modules for Node and consists provides the feature of the encryption of
of command line client npm. NPM gets installed into communication with the help of the secure layer
the system with installation of Node. The required feature of this module. Whereas the HTTP module
packages and modules in Node project are installed doesn’t provide the encryption of the data.
using NPM. A package contains all the files needed
for a module and modules are the JavaScript libraries Q17> Write steps to handle http requests while
that can be included in Node project according to the creating web server using node.JS?
requirement of the project. NPM can install all the / Step 1: Import the HTTP module const http =
dependencies of a project through the package.json require('http'); // Step 2: Create the server using the
file. It can also update and uninstall packages. In the http. createServer() method const server = http.
package.json file, each dependency can specify a createServer((req, res) => { // Step 3: Set the
range of valid versions using the semantic versioning response headers res. writeHead(200, {'Content-Type':
scheme, allowing developers to auto-update their 'text/plain'}); // Step 4: Send the response body res.
packages while at the same time avoiding unwanted
breaking changes. Needs of npm 1>Adapt Q18> What is Synchronous and Asynchronous
packages of code for your apps, or incorporate approach?
packages as they are.2>Download standalone tools Synchronous learning refers to all types of learning in
you can use right away. 3>Run packages without which learner(s) and instructor(s) are in the same
downloading using npx. 4>Share code with any npm place, at the same time, in order for learning to take
user, anywhere. 5>Restrict code to specific place. This includes in-person classes, live online
developers. meetings when the whole class or smaller groups get
together. Synchronous learning refers to instructors
Q12>package in node js? and students gathering at the same time and (virtual
A package in Node.js contains all the files you need or physical) place and interacting in “real-time”.
for a module. Modules are JavaScript libraries you Asynchronous learning refers to students accessing
can include in your project. materials at their own pace and interacting with each
other over longer periods.
Q13>install local package? Asynchronous learning means that the instructor and
Step 1: Go to the local module directory ( package the students in the course all engage with the course
you want to install ) and enter this command. npm content at different times (and from different
link locations). The instructor provides students with a
sequence of units which the students move through
as their schedules permit. Asynchronous learning
means that the instructor and the students in the Q20> operation of file in node js
course all engage with the course content at different The file can be read and written in node. js in both
times (and from different locations). The instructor Synchronous and Asynchronous ways. A
provides students with a sequence of units which the Synchronous method is a code-blocking method
students move through as their schedules permit. which means the given method will block the
execution of code until its execution is finished (i.e.
Complete file is read or written).

Q19> read a file


The fs.readFile() method is an inbuilt method that is
used to read the file. This method read the entire file Q21> Explain Event Driven Programming?
into the buffer. To load the fs module we use Event-driven programming (EDP) is a programming
require() method. For example: var fs = require(‘fs’); paradigm where external events determine the flow
Syntax:mfs.readFile(filename,encoding, of program execution. These events come in different
callback_function ) Parameters: The method accepts shapes: user actions (e.g., button clicks, keyboard
three parameters as mentioned above and described inputs), system events (like a finished file download),
below: filename: It holds the name of the file to read messages from other programs, sensor outputs, etc
or the entire path if stored at another location. Enables asynchronous processing, optimizing
encoding: It holds the encoding of the file. Its default resource utilization and responsiveness, crucial for
value is ‘utf8’. callback_function: It is a callback real-time applications and user interfaces.
function that is called after reading of file. It takes Encourages modular code design, simplifying
two parameters: err: If any error occurred. data: maintenance and scalability by separating concerns
Contents of the file. and promoting code reusability. Enhances user
experience by responding promptly to user inputs,
Q21 How does node.JS handles a file request? delivering a smoother and more interactive interface.
The most important functionalities provided by Facilitates easier integration of new features or
programming languages are Reading and Writing modifications, promoting adaptability to changing
files from computers. Node.js provides the requirements in dynamic environments. Components
functionality to read and write files from the communicate through events, reducing
computer. Reading and Writing the file in Node.js is dependencies and enhancing system flexibility,
done by using one of the coolest Node.js modules making it easier to maintain and modify.
called fs module, it is one of the most well-known
built-in Node.js modules out there. The file can be Q21> EventEmitter class.
read and written in node.js in both Synchronous and Node.js uses events module to create and handle
Asynchronous ways. A Synchronous method is a custom events. The EventEmitter class can be used
code-blocking method which means the given to create and handle custom events module.
method will block the execution of code until its Syntax:const EventEmitter = require('events');
execution is finished (i.e. Complete file is read or The EventEmitter class can be used to create and
written). On the other hand, an Asynchronous method handle custom events module. The syntax to Import
has a callback function that is executed on the events module are given below: Syntax: const
completion of the execution of the given method and EventEmitter = require('events'); All EventEmitters
thus allows code to run during the completion of its emit the event newListener when new listeners are
execution. Or according to modern JavaScript, added and removeListener when existing listeners
asynchronous methods return a Promise which are removed
implies the eventual completion of the ongoing
asynchronous method, the Promise will either be Q21> inheriting events in node js?’
resolved or rejected. Thus, it is non-blocking. The “util” module provides ‘utility’ functions that are
Synchronous method to read the file: To read the file used for debugging purposes. For accessing those
in the synchronous mode we use a method in the fs functions we need to call them (by ‘require(‘util’)‘).
module which is readFileSync(). It takes two The util.inherits() (Added in v0.3.0) method is an
parameters first is the file name with a complete path inbuilt application programming interface of the util
and the second parameter is the character encoding module in which the constructor inherits the
which is generally ‘utf-8’. prototype methods from one to another and the
prototype of that constructor is set to a new object
which is created from superConstructor. It is mostly
used for adding or inheriting some input validation on
top of
Object.setPrototypeOf(constructor.prototype,superCo
nstructor.prototype). And superConstructor can be
accessed through the constructor.super_property for
additional convenience. Its (i.e, util.inherits()) usage
is not much encouraged instead use of ES6 class and
extends keywords is recommended in order to get
language level inheritance support.
Syntax:
const util = require('util');
util.inherits(constructor, superConstructor)
Q22> CREATING DATABASE IN MYSQL SERVER?
Creating a database is one of the most fundamental
tasks while working with MYSQL. A database serves
as a container for tables, views, procedures, and
several other database objects. The CREATE
DATABASE statement is used in MYSQL to create a
new database that will store all the tables that the
user will create to store the data.1. Create a
Database Using the MySQL Command Line Client 2.
Open the application and then Enter your password.
3. Run the following command to check the existing
databases in the system. 4. After that run the
following command to create database of your
choice. 5. Again run the SHOW Databases
command and you will see your database is created.
6. Run the following command to use the database
you have just created.

Q21> Explain fs.readfile( ) method for all possible


values of options?
The fs.readFile() method is an inbuilt method that is
used to read the file. This method read the entire file
into the buffer. To load the fs module we use
require() method. For example: var fs = require(‘fs’
);Parameters: The method accepts three parameters
as mentioned above and described below: filename:
It holds the name of the file to read or the entire path
if stored at another location. encoding: It holds the
encoding of the file. Its default value is ‘utf8’.
callback_function: It is a callback function that is
called after reading of file. It takes two parameters:
err: If any error occurred. data: Contents of the file.
host: "localhost", user: "root", password: "iccs#123"
database: "college", port: '3308'
});
con. connect (function (err) {
if (err) throw err;
con. query ("SELECT * FROM student", function (err,
result, fields) f
if (err) throw err;
//Showing all the records console. log(result);
3) ;
3) ;

Q26> Write a program to write to a file in node.JS.


const fs = require('fs');
const filePath = 'output.txt';
Q23> Write a program to update table records using const content = 'Hello, this is some content that will
node. JS and MYSQL database be written to the file.';
const prompt = require( 'prompt-sync')(); fs.writeFile(filePath, content, (err) => {
var mysql = require( 'mysql'); if (err) {
var con = mysql. createConnection (f console.error('Error writing to file:', err);
host: "localhost", user: "root", password: "iccs#123", return;
database: "college", port: '3308' }
7); console.log('Content has been written to', filePath);
con. connect (function (err) { });
if (err) throw err;
const cityName = prompt ("Enter City Name::");
var sql = "DELETE from student WHERE stud_city ='" +
cityName + ';
//Executing the above query
con. query (sql, function (err, result) t
if (err) throw err;
console. log(result. affectedRows + " record(s)
deleted");
}) ;
}) ;
Q24> Write a program which uses addlistener ( )
method of Event Emmitter class.
 const EventEmitter = require( 'events');
var eventEmitter = new EventEmitter();
var fun1 = (msg) => {
console. log("Message from fun1: " + msg);
};
var fun2 = (msg) => {
console. log ("Message from fun2: " + msg);
event Emitter.addListener ('myEvent', fun1);
eventEmitter. prependListener ('myEvent', fun2);
console. log(eventEmitter. listeners( 'myEvent'));
console. log(eventEmitter. listenerCount ('myEvent'));
eventEmitter. emit('myEvent', 'Event occurred');

q25>Write a program to use SQL SELECT Qvery to


show data from a table using node. JS and
MYSQLdata base.
var mysql = revire('mysq1');
var con = mysql. createConnection(f

You might also like