[go: up one dir, main page]

0% found this document useful (0 votes)
28 views7 pages

Chapter 3

Good Knowledge

Uploaded by

Ganesh Hasnale
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)
28 views7 pages

Chapter 3

Good Knowledge

Uploaded by

Ganesh Hasnale
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/ 7

Chapter-3 Node Package Manager

3.1 What is npm?


3.2 Installing Packages Locally
3.3 Adding dependency in package.json
3.4 Installing packages globally
3.5 Updating packages

Introduction to npm : Npm stands for Node Package Manager. It is a package manager for the Node
JavaScript platform. Npm is known as the world’s largest software registry. Open-source developers all over
the world use npm to publish and share their source code.

Npm consists of three components:

● The website allows you to find third-party packages, set up profiles, and manage your packages.
● The command-line interface or npm CLI that runs from a terminal to allow you to interact with npm.
● The registry is a large public database of JavaScript code.

Using npm is Free

npm is free to use. You can download all npm public software packages without any registration or logon.

Command Line Client : npm includes a CLI (Command Line Client) that can be used to download and
install software:
Windows Example
C:\>npm install <package>

To find the npm CLI on your computer, you run the npm command from a terminal:

npm

For example, the following command will display the current npm version on your system:

npm -v
Software Package Manager

The name npm (Node Package Manager) stems from when npm first was created as a package manager for
Node.js.

All npm packages are defined in files called package.json.

The content of package.json must be written in JSON.

At least two fields must be present in the definition file: name and version.

package.json : In general, every npm project has a file called package.json located in the root directory.
The package.json is a plain text file that contains important information that npm uses to identify the project
and handle dependencies. To create the package.json file, you go to the root directory of the project and
execute the following command:
npm init

When you run the npm init command, it will prompt you for the project information including:

● Package name
● Version
● Test command
● Git repository
● Keywords
● Author
● License

If you hit Return or Enter, it will accept the default values and move on to the next prompt.

If you want to use default options, you use the following command:

npm init --yes

Later, you can change the default values in the package.json.

Install a new package


To install a new package, you use the following npm install command:
npm install <package_name>
Code language: JavaScript (javascript)
In this command, you place the package name after the npm install keywords.
To find packages, you go to the npm website and search for them.

To save some typing, you can use a shorter version of the npm install command:

npm i <package_name>
Code language: JavaScript (javascript)

In this command, i stands for install.

there are several ways to run npm commands. Below are the brief lists of some of the commonly used npm
commands (or aliases).

o npm i : install local package


o npm i -g : install global package
o npm un : uninstall local package
o npm up: npm update packages
o npm t: run tests
o npm ls: list installed modules
o npm ll or npm la: print additional package information while listing modules

What is a Package?

A package in Node.js contains all the files you need for a module.
Modules are JavaScript libraries you can include in your project.

Download a Package

Downloading a package is very easy.

Open the command line interface and tell NPM to download the package you want.

I want to download a package called "upper-case":

Download "upper-case":

C:\Users\Your Name>npm install upper-case

Now you have downloaded and installed your first package!

NPM creates a folder named "node_modules", where the package will be placed. All packages you install in
the future will be placed in this folder.

My project now has a folder structure like this:

C:\Users\My Name\node_modules\upper-case

Using a Package

Once the package is installed, it is ready to use.

Include the "upper-case" package the same way you include any other module:

var uc = require('upper-case');

Create a Node.js file that will convert the output "Hello World!" into upper-case letters:

var http = require('http');

var uc = require('upper-case');

http.createServer(function (req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

/*Use our upper-case module to upper case a string:*/

res.write(uc.upperCase("Hello World!"));

res.end();

}).listen(8080);

Save the code above in a file called "demo_uppercase.js", and initiate the file:

Initiate demo_uppercase:
C:\Users\Your Name>node demo_uppercase.js

If you have followed the same steps on your computer, you will see the same result as the
example: http://localhost:8080

Express:

Express is a minimal and flexible Node.js web application framework that provides a robust set of features
to develop web and mobile applications. It facilitates the rapid development of Node based Web
applications. Following are some of the core features of Express framework −
● Allows to set up middlewares to respond to HTTP Requests.
● Defines a routing table which is used to perform different actions based on HTTP Method and URL.
● Allows to dynamically render HTML Pages based on passing arguments to templates.

Express.Js

Advantages of Express.js

1. Makes Node.js web application development fast and easy.


2. Easy to configure and customize.
3. Allows you to define routes of your application based on HTTP methods and URLs.
4. Includes various middleware modules which you can use to perform additional tasks on request and
response.
5. Easy to integrate with different template engines like Jade, Vash, EJS etc.
6. Allows you to define an error handling middleware.
7. Easy to serve static files and resources of your application.
8. Allows you to create REST API server.
9. Easy to connect with databases such as MongoDB, Redis, MySQL

Installing Express
Firstly, install the Express framework globally using NPM so that it can be used to create a web application
using node terminal.
$ npm install express --save
The above command saves the installation locally in the node_modules directory and creates a directory
express inside node_modules. You should install the following important modules along with express −
● body-parser − This is a node.js middleware for handling JSON, Raw, Text and URL encoded form
data.
● cookie-parser − Parse Cookie header and populate req.cookies with an object keyed by the cookie
names.
● multer − This is a node.js middleware for handling multipart/form-data.
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save
Hello world Example : Following is a very basic Express app which starts a server and listens on port 8081
for connection. This app responds with Hello World! for requests to the homepage. For every other path, it
will respond with a 404 Not Found.

var express = require('express');


var app = express();

app.get('/', function (req, res) {


res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Save the above code in a file named server.js and run it with the following command.
ou will see the following output −
Example app listening at http://0.0.0.0:8081
Open http://127.0.0.1:8081/ in any browser to see the following result.

Request & Response


Express application uses a callback function whose parameters are request and response objects.

Web Server : First of all, import the Express.js module and create the web server as shown below.
app.js: Express.js Web Server
Example :

var express = require('express');


var app = express();

// define routes here..

var server = app.listen(5000, function () {


console.log('Node server is running..');
});
In the above example, we imported Express.js module using require() function. The express module returns
a function. This function returns an object which can be used to configure Express application (app in the
above example).
The app object includes methods for routing HTTP requests, configuring middleware, rendering HTML
views and registering a template engine.
The app.listen() function creates the Node.js web server at the specified host and port. It is identical to
Node's http.Server.listen() method.
Run the above example using node app.js command and point your browser to http://localhost:5000. It will
display Cannot GET / because we have not configured any routes yet.
Configure Routes : Use app object to define different routes of your application. The app object includes
get(), post(), put() and delete() methods to define routes for HTTP GET, POST, PUT and DELETE requests
respectively.
The following example demonstrates configuring routes for HTTP requests.
Example: Configure Routes in Express.js

var express = require('express');

var app = express();

app.get('/', function (req, res) {


res.send('<html><body><h1>Hello World</h1></body></html>');
});

app.post('/submit-data', function (req, res) {


res.send('POST Request');
});

app.put('/update-data', function (req, res) {


res.send('PUT Request');
});

app.delete('/delete-data', function (req, res) {


res.send('DELETE Request');
});

var server = app.listen(5000, function () {


console.log('Node server is running..');
});
In the above example, app.get(), app.post(), app.put() and app.delete() methods define routes for HTTP
GET, POST, PUT, DELETE respectively. The first parameter is a path of a route which will start after base
URL. The callback function includes request and response object which will be executed on each request.
Run the above example using node server.js command, and point your browser to http://localhost:5000 and
you will see the following result.

Express.js
Web Application

You might also like