0% found this document useful (0 votes)
4 views17 pages

Unit 1 Node js

Node.js is an open-source, cross-platform server environment that uses JavaScript for server-side programming and supports asynchronous, non-blocking operations. It allows for dynamic content generation, file manipulation, and database interactions, and is bundled with npm, a package manager for managing project dependencies. The document also covers the REPL environment, blocking vs non-blocking operations, and provides examples of using Node.js and npm for application development.

Uploaded by

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

Unit 1 Node js

Node.js is an open-source, cross-platform server environment that uses JavaScript for server-side programming and supports asynchronous, non-blocking operations. It allows for dynamic content generation, file manipulation, and database interactions, and is bundled with npm, a package manager for managing project dependencies. The document also covers the REPL environment, blocking vs non-blocking operations, and provides examples of using Node.js and npm for application development.

Uploaded by

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

Unit – 1 Node Js

What is Node.js?
 Node.js is an open source server environment
 Node.js is free
 Node.js runs on various platforms (Windows, Linux, Unix,
Mac OS X, etc.)
 Node.js uses JavaScript on the server

Why Node.js?
 Node.js uses asynchronous programming!
 A common task for a web server can be to open a file on
the server and return the content to the client.
 Here is how PHP or ASP handles a file request:
 Sends the task to the computer's file system.
 Waits while the file system opens and reads the file.
 Returns the content to the client.
 Ready to handle the next request.
 Here is how Node.js handles a file request:
 Sends the task to the computer's file system.
 Ready to handle the next request.
 When the file system has opened and read the file, the
server returns the content to the client.
 Node.js eliminates the waiting, and simply continues with
the next request.
 Node.js runs single-threaded, non-blocking, asynchronous
programming, which is very memory efficient.

What Can Node.js Do?


 Node.js can generate dynamic page content
 Node.js can create, open, read, write, delete, and close
files on the server
 Node.js can collect form data
 Node.js can add, delete, modify data in your database

 What is a Node.js File?


 Node.js files contain tasks that will be executed on certain
events
 A typical event is someone trying to access a port on the
server
 Node.js files must be initiated on the server before having
any effect
 Node.js files have extension ".js"

/Installing Download Node.js


The official Node.js website has installation instructions for
Node.js: https://nodejs.org

Once you have downloaded and installed Node.js on your computer, let's try
to display "Hello World" in a web browser.

Create a Node.js file named "myfirst.js", and add the following


code:

const http = require('node:http');

const hostname = '127.0.0.1';


const port = 3000;

const server = http.createServer((req, res) => {


res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {


console.log(`Server running at http://${hostname}:${port}/`);
});

Save the file on your computer: C:\Users\Your Name\


myfirst.js
What is npm
npm is a short form of Node Package Manager, which is
the world's largest software registry. The open-source
web project developers use it from the entire world
to share and borrow packages. The npm also acts as a
command-line utility for the Node.js project for
installing packages in the project, dependency
management, and even version management.

Components of npm
npm mainly consists of three different components,
these are:
1. Website: The npm official website is used to find
packages for your project, create and set up
profiles to manage and access private and public
packages.
2. Command Line Interface (CLI): The CLI runs
from your computer's terminal to interact with npm
packages and repositories.
3. Registry: The registry is a large and public
database of JavaScript projects and meta-
information. You can use any supported npm
registry that you want or even your own. You can
even use someone else's registry as per their
terms of use.

When to use npm


o Use npm to adapt packages of code for your apps
or incorporate packages as they are.
o Use npm when you need to share code with any
npm user, anywhere.
o npm can be used when you want to restrict code to
specific developers.
o Use npm to create organizations to coordinate

package maintenance, coding, and developers.


o Use npm to manage multiple versions of code and

code dependencies.
o Use npm to update applications easily when the

underlying code is updated.


o Use npm to find other developers who are working

on similar problems and projects.


This means that you have to install Node.js to get npm
installed on your computer.
Download Node.js from the official Node.js web
site: https://nodejs.org

How to Use NPM with Node.js?


To start using NPM in your project, follow these simple
steps
Step 1: Install Node.js and NPM
First, you need to install Node.js. NPM is bundled with
the Node.js installation. You can follow our article to
Install the Node and NPM- How to install Node on your
system
Step 2: Verify the Installation
After installation, verify Node.js and NPM are installed
by running the following commands in your terminal:

node -v
npm -v
These commands will show the installed versions of
Node.js and NPM.

Step 3: Initialize a New Node.js Project


In the terminal, navigate to your project directory and
run:
npm init -y
This will create a package.json file, which stores
metadata about your project, including dependencies
and scripts.
Step 4: Install Packages with NPM
To install a package, use the following command
For example, to install the Express.js framework
npm install express

This will add express to the node_modules folder and


automatically update the package.json file with the
installed package information.
Using NPM Package in the project
Create a file named app.js in the project
directory to use the package
//app.js

const express = require('express');//import the


required package
const app = express();

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


res.send('Hello, World!');
});

app.listen(3000, () => {
console.log('Server running at
http://localhost:3000');
});
 express() creates an instance of the Express app.

 app.get() defines a route handler for HTTP GET

requests to the root (/) URL.


 res.send() sends the response “Hello, World!” to

the client.
 app.listen(3000) starts the server on port 3000,

and console.log() outputs the server URL.


Now run the application with
node app.js
Visit http://localhost:3000 in your browser, and you
should see the message: Hello, World!

Popular NPM Packages


NPM has a massive library of packages. Here are a few
popular packages that can enhance your Node.js
applications:
 Express: A fast, minimal web framework for
building APIs and web applications.
 Mongoose: A MongoDB object modeling tool for

Node.js.
 Lodash: A utility library delivering consistency,

customization, and performance.


 Axios: A promise-based HTTP client for making

HTTP requests.
 React: A popular front-end library used to build

user interfaces.
What is Node.js REPL?
REPL stands for:
 Read: The REPL reads user input (JavaScript code).

 Eval: The input is evaluated (executed) by

the JavaScript engine.


 Print: The result of the evaluation is printed to the

screen.
 Loop: The process repeats (loops), waiting for the

next input.
 This interactive environment allows developers to test small
snippets of code without needing to create a full script. The
REPL is built directly into Node.js, so no additional setup is
required.
 The Node.js REPL environment allows developers to test
code snippets quickly. To build real-world full-stack
applications .
Getting Started with REPL
To start working with REPL environment of NODE; open up the
terminal (in case of UNIX/LINUX) or the Command prompt (in
case of Windows) and write node and press ‘enter’ to start the
REPL.

Node
The REPL has started and is demarcated by the ‘>’
symbol. Various operations can be performed on the
REPL. Below are some of the examples to get familiar
with the REPL environment.
Key Features of Node.js REPL
1. Executing JavaScript Code
The REPL is a full-featured JavaScript environment,
meaning you can run any valid JavaScript code inside it.
Example:

> const x = 10;


> const y = 20;
>x+y
30

You can declare variables, create functions, and run any


code that would work in a regular JavaScript runtime.
2. Multi-Line Input
In case of complex logic (like loops or functions), the
REPL supports multi-line input. When you enter a block
of code, the REPL will continue reading input until the
block is complete.
Example:
> function add(a, b) {
... return a + b;
... }
> add(5, 10)
15
Here, the REPL waits for you to complete the function
block before evaluating the code.
3. Underscore (_) Variable
The REPL provides a special variable _ (underscore)
that stores the result of the last evaluated expression.
Example:
>3+3
6
>_*2
In this case, the result of 3 + 3 is stored in _, which is
then used in the next line to calculate 12.
4. Saving and Loading REPL Sessions
The REPL allows you to save the session output to a file
and load previously saved sessions, making it easier to
keep track of the code you’ve tested.
Saving a Session: To save your REPL session to a file,
use the .save command:
> .save ./repl_session.js
Loading a Session: You can load the saved session
into a new REPL session using .load:
> .load ./repl_session.js
5. Accessing Node.js Core Modules
The REPL environment allows you to load and use
Node.js core modules, such as fs, path, http, etc.,
without needing to exit the REPL or write an entire
script.
Example:
> const fs = require('fs');
> fs.readFileSync('test.txt', 'utf8');
In this example, the fs (file system) module is loaded,
and the REPL reads the content of a file named test.txt.
6. Error Handling in REPL
The REPL is forgiving of errors and will display helpful
error messages without crashing the entire session.
This makes it a safe environment for testing.
Example:
> console.log(foo);
ReferenceError: foo is not defined
Built-in REPL Commands
Node.js REPL provides several built-in commands (REPL
commands always start with a dot .).
 .help: Displays a list of all available REPL

commands.
 .break: Breaks out of multi-line input or clears the

current input.
 .clear: Resets the REPL context by clearing all

declared variables.
 .exit: Exits the REPL session.
 Example: Performing Arithmetical operations in REPL


 Example: Performing operations using libraries of NODE.
 MATH library is being used in below example.

Note: using ‘math’ shows error as the library is


referenced as ‘Math’ in NODE and not ‘math’.
Example: Using variables in REPL. The keyword var is
used to assign values to variables.

What is Blocking?
It refers to the blocking of further operation until the
current operation finishes. Blocking methods are
executed synchronously. Synchronously means that the
program is executed line by line. The program waits
until the called function or the operation returns.
Example: Following example uses
the readFileSync() function to read files and
demonstrate Blocking in Node.js

const fs = require('fs');

const filepath = 'text.txt';

// Reads a file in a synchronous and blocking way


const data = fs.readFileSync(filepath, {encoding:
'utf8'});

// Prints the content of file


console.log(data);

// This section calculates the sum of numbers from 1 to


10
let sum = 0;
for(let i=1; i<=10; i++){
sum = sum + i;
}

// Prints the sum


console.log('Sum: ', sum);
Run the index.js file using the following command:
node index.js
Output:
This is from text file.
Sum: 55

What is Non-Blocking ?
It refers to the program that does not block the
execution of further operations. Non-Blocking methods
are executed asynchronously. Asynchronously means
that the program may not necessarily execute line by
line. The program calls the function and move to the
next operation and does not wait for it to return.
Example: Following example uses
the readFile() function to read files and demonstrate
Non-Blocking in Node

const fs = require('fs');

const filepath = 'text.txt';

// Reads a file in a asynchronous and non-blocking way


fs.readFile(filepath, {encoding: 'utf8'}, (err, data) => {
// Prints the content of file
console.log(data);
});
// This section calculates the sum of numbers from 1 to
10
let sum = 0;
for(let i=1; i<=10; i++){
sum = sum + i;
}

// Prints the sum


console.log('Sum: ', sum);
Run the index.js file using the following command:
node index.js
Output:
Sum: 55
This is from text file.

Node.js Callbacks
Callback is an asynchronous equivalent for a function. It
is called at the completion of each task. In Node.js,
callbacks are generally used. All APIs of Node are
written in a way to supports callbacks. For example:
when a function start reading file, it returns the control
to execution environment immediately so that the next
instruction can be executed.
In Node.js, once file I/O is complete, it will call the
callback function. So there is no blocking or wait for File
I/O. This makes Node.js highly scalable, as it can
process high number of request without waiting for any
function to return result.
Blocking Code Example
Follow these steps:
1. Create a text file named input.txt having the
following content:
1. Parul University is NAAC A++ accredited
private university in Vadodara, Gujarat.
Explore our diverse educational programs
2. different technologies, in a very simple langua
ge.
2. Create a JavaScript file named main.js having the
following code:
1. var fs = require("fs");
2. var data = fs.readFileSync('input.txt');
3. console.log(data.toString());
4. console.log("Program Ended");
3. Open the Node.js command prompt and execute
the following code.
1. node main.js
Non Blocking Code Example
Follow these steps:
Create a text file named input.txt having the following
content:
1. Parul University is NAAC A++ accredited private
university in Vadodara, Gujarat. Explore our diverse
educational programs
2. different technologies, in a very simple language.

Create a JavaScript file named main.js having the


following code:
1. var fs = require("fs");
2. fs.readFile('input.txt', function (err, data) {
3. if (err) return console.error(err);
4. console.log(data.toString());
5. });
6. console.log("Program Ended");
Open the Node.js command prompt and execute the
following code.
1. node main.js

You might also like