0% found this document useful (0 votes)
9 views

MSD (U3) SLIPS

Unit -3 ,Subject : mean stack. For btech cse students all over the india. Notes purpose
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)
9 views

MSD (U3) SLIPS

Unit -3 ,Subject : mean stack. For btech cse students all over the india. Notes purpose
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/ 16

Modular programming Node Package

(U3)
in Node.js
(U3)
Manager (NPM)
Modularisation definition Node Package Manager (npm) is the
Modularization is a software design default package manager for Node.js. It is
technique in which the functionality of a used to Install and manage packages,
program is separated into independent which are collections of code and
modules so, that each module contains dependencies that can be shared and
thedesired functionality. reused in different Node.js projects
Modular programming is an →Installing packages in
important concept in Node.js, as it allows you our application
to break down a Complex Node.js application
into smaller, more manageable modules that To install any NPM package use the below
can be developed and tested independently. code in the command prompt:
npm install <package_name>[@<version]
creating a module: In Node.js, you can
create a module by creating a new →modes of installation of
javaScript file and exporting its packages through NPM:
functionality using the module.exports object. 1)Global installation: To globally install
// myModule.js any package or tool add -g to the
function myFunction() { command. On installing any package
console.log('Hello World!'); globally, that package gets added to the
} PATH so that it can be run from any
module.exports = myFunction; location on the computer
Importing module npm install -g <package_name>
To use this module in another file, you can 2)Local installation: If -g is not added
use the require function to import it: to the command for installation then,
// main.js the modules get installed locally, within
Const myFunction = require('./myModule'); a node_modules folder under the root
myFunction(); // logs 'Hello World!' directory. This is the default mode, as
Advantages of modularization well.
1)Readability:-Modular code highly npm install express
organizes the program based on its →key features of npm:
functionality. This allows the developers to
1)Dependency management: npm
understand what each piece of code does in
allows you to specify dependencies for
the application.
your Node.js project in a package.json
2)easier to debug:-When debugging file, which lists all the required packages
large programs, it is difficult to detect bugs. and their versions.This makes it easy to
If a program is modular, then each module is manage and share your project's
discrete, so each module can be debugged dependencies with others.
easily by the programmer. 2)Package publishing: You can publish
3)Reliability:- Modular code will be easier your own packages to the npm registry,
to read. Hence it will be easier to debug and which can be used by others in their
maintain the code which ensures smoother own projects.
execution with minimum errors.
File Operations Restarting Node
(U3) in Node.js (U3)
Application
File:- A file is a collection of data stored
in a Computer system. Typically, these files When you are developing a Node.js
are used for storing information about application, you may need to restart the
users,software applications, or other data application multiple times to see the
that are needed for running programs. changes you've made.
→FILE OPERATIONS ways to restart Node.js
Node.js provides a built-in module called fs Application:
(short for file system) that allows you to (1) Manually: You can simply stop the
perform file operations such as reading and running Node.js process in the terminal by
writing files. Here are some common file pressing Ctrl + C, and then start it again
operations that you can perform using the using the node command. This method is
fs module in Node.js: suitable for small applications or for
(a)Reading a file:You can use the development purposes.
fs.readFile method to read the contents of (2) Using nodemon: nodemon is a tool
a file asynchronously. that monitors changes in your Node.js
example: application and automatically restarts the
const fs = require('fs'); server when changes are detected. To use
fs.readFile('file.txt', 'utf8', (err, data) => { nodemon, you need to install it globally
if (err) throw err; using npm:
console.log(data); npm install -g nodemon
}); Once installed, you can use the nodemon
In this example, we use the fs.readFile command to start your application:
method to read the contents of a file nodemon app.js
named file.txt. Now, whenever you make changes to your
(b)Writing to a file:You can use the fs. application, nodemon will detect them and
automatically restart the server.
writeFile method to write data to a file
asynchronously.
(3) Using PM2: PM2 is a process
manager for Node.js applications that
example: provides advanced features such as
const fs = require('fs'); automatic restart, monitoring, and logging.
fs.writeFile('file.txt', 'Hello World!', (err) => { To use PM2, you need to install it globally
if (err) throw err; using npm:
console.log('Data written to file'); npm install -g pm2
}); Once installed, you can use the pm2 start
(C)Renaming a file: You can use the command to start your application:
fs.rename method to rename a file pm2 start app.js
asynchronously PM2 will monitor your application and
Example automatically restart it if it crashes or if
Const fs = require('fs'); changes are detected.
fs.rename('file.txt', 'newfile.txt', (err) => { You can also use the pm2 list command to
if (err) throw err; see a list of all running applications, and
console.log('File renamed'); the pm2 logs command to view the logs
}); for a specific application.
Creating a web server (U3)Node.js definition
(U3) in Node.js
Node.js is an open-source, cross-platform
JavaScript runtime environment built on
→Web server definition Chrome's V8 JavaScript engine. It allows
A web server is a computer system developers to run JavaScript on the
combined with software used for the storing server-side and build fast, scalable, and
and serving of website files. efficient network applications. Node.js has
a rich set of built-in modules and
→Steps in creating a web server packages available in the NPM (Node
To create a web server in Node.js, you can Package Manager) repository, making it
use the built-in HTTP module easy for developers to quickly build web
Step 1: Create a new JavaScript file applications, APIs, and microservices.
httpserver.js and include the HTTP module.
Const http = require("http");
APPLICATIONS OF
Step 2: Use the createServer() method of the NODE.JS
HTTP module to create a web server.
1)Web Development: Node.js is
→ var server = http.createServer((req, commonly used for building server-side
res) => { web applications and APIs. It's particularly
popular for real-time web applications,
→ res.write("Hello World! I have
such as chat apps and online gaming
created my first server!"); platforms.
→ res.end(); 2)Microservices: Its event-driven
architecture and lightweight nature make
→ }); Node.js well-suited for building
→ server.listen(3000); microservices architectures.
→ console.log("Server started...Running 3)Streaming Applications: Node.js is
great for handling I/O-bound operations,
on localhost:3000"); making it ideal for building streaming
Step 3: Save the file and start the server applications like video and audio
streaming services.
using the node command. When the file
4)Single Page Applications (SPAs): Node.
executes successfully, the following js can serve as a backend for SPAs,
output can be observed in the console. providing the necessary APIs and handling
data retrieval and processing.
D:\NodeJS>node httpserver
5)IoT (Internet of Things):- Node.js is
Server started...Running on localhost:3000 lightweight and well-suited for IoT
Step 4: Observe the " localhost:3000 " in applications, enabling developers to build
IoT devices and applications efficiently.
the browser. 6)Desktop Applications: With
Thus, a Node server has been created and frameworks like Electron, developers can
sent the response from the server to the use Node.js to build cross-platform
desktop applications using web
client technologies like HTML.
(U3) Advantages of Node.js (U3)
Using Node.js for building web servers offers How to write data to
several advantages:
1)Asynchronous and Non-blocking: Node. the console in node js
js uses an event-driven, non-blocking I/O
model , making it efficient for handling a large
In Node.js, you can write data to
number of connections simultaneously
without consuming a lot of system the console using the `console`
resources. This allows for high scalability and module.
better performance. a sample code demonstrating
2)JavaScript Everywhere: Node.js allows how to write data to the
developers to use JavaScript on both the console:
client-side and server-side, enabling full-
stack development with a single // Import the console module
programming language. This simplifies the const console = require('console');
development process and reduces the // Write a string to the console
learning curve for developers. console.log("Hello, world!");
3)Large Ecosystem:Node.js has a vast // Write an object to the console
ecosystem of libraries and packages available const person = {
through npm (Node Package Manager), name: "John Doe",
which allows developers to easily integrate
age: 30,
third-party modules into their applications.
This accelerates development and enables city: "New York"
developers to leverage existing solutions for };
common tasks. console.log(person);
4)Fast Execution:Node.js is built on the V8 //Write formatted output to the console
javaScript engine, which is known for its const num1 = 10;
high performance. This allows Node.js const num2 = 20;
applications to execute quickly and handle a console.log(`The sum of ${num1}
large number of concurrent requests and ${num2} is ${num1 + num2}.`);
efficiently.
5.)Community Support: Node.js has a This code demonstrates various
large and active community of developers
who contribute to its development and ways to use the `console.log()`
provide support through forums, tutorials, method to write data to the
and documentation. This vibrant community console in Node.js. You can output
ensures that developers have access to strings, objects, and formatted
resources and assistance when building messages using template literals.
Node.js applications.
6)Real-time Applications:Node.js is well-
suited for building real-time applications,
such as chat applications and online gaming
platforms, that require low-latency
communication between the client and
server.

You might also like