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

Node Js

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Node Js

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Node.

js
Introduction to Node.js
Node.js is an open source server environment.

Node.js allows you to run JavaScript on the server.

Node.js has a set of built-in modules.

Built-in Modules

Download Node.js
Download Node.js from the official Node.js web site: https://nodejs.org
Introduction to 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!
What is a Server?

A server stores, sends, and receives data. In essence, it "serves"


something else and exists to provide services. A computer,
software program, or even a storage device may act as a server,
and it may provide one service or several.
Introduction to Node.js

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"

Test Server using Node
Create a Node.js file named "myfirst.js", and add the following code:

var http = require('http');

http.createServer(function (req, res) {

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

res.end('Hello World!');

}).listen(8080);

Initiate the Node.js File

The file you have just created must be initiated by Node.js before any action can take place.

Start your command line interface, write node myfirst.js and hit enter:
Test Server using Node

Initiate the Node.js File


The file you have just created must be initiated by Node.js before any action can take place.

Start your command line interface, write node myfirst.js and hit enter:

Start your internet browser, and type in the address: http://localhost:8080


What is a Module in Node.js?

Consider modules to be the same as JavaScript libraries.

A set of functions you want to include in your application.

Built-in Modules
Node.js has a set of built-in modules which you can use without any further installation.

Look at our Built-in Modules Reference for a complete list of modules.


Built-in Modules

To include a module, use the require() function with the name of the module:

var http = require('http');

Now your application has access to the HTTP module, and is able to create a server:

http.createServer(function (req, res) {

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

res.end('Hello World!');

}).listen(8080);
Create Your Own Modules

You can create your own modules, and easily include them in your applications.

The following example creates a module that returns a date and time object:

Example
Get your own Node.js Server

Create a module that returns the current date and time:

myfirstmodule.js

exports.myDateTime = function () {

return Date();
Use the exports keyword to make
}; properties and methods available
outside the module file.
Include Your Own Module

Example
Use the module "myfirstmodule" in a Node.js file:

var http = require( 'http' );

var dt = require( './myfirstmodule' );

http.createServer( function (req, res) {

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

res.write( "The date and time are currently: " + dt.myDateTime());

res.end();

}).listen( 8080);
Node.js HTTP Module
Node.js HTTP Module
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 HTTP Module
Node.js as a Web Server
The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Use the createServer() method to create an HTTP server:

The function
passed into the
http.createSe
rver() method,
will be executed
when someone
tries to access
the computer on
port 8080.
Node.js HTTP Module
Initiate demo_http.js:

C:\Users\Your Name>node demo_http.js

http://localhost:8080
Node.js HTTP Module
Add an HTTP Header
If the response from the HTTP server is supposed to be displayed as HTML, you should include an HTTP header
with the correct content type:

The first argument


of the
res.writeHead()
method is the status
code, 200 means
that all is OK, the
second argument is
an object containing
the response
headers.
Node.js HTTP Module
Read the Query String
The function passed into the http.createServer() has a req argument that represents the request from the
client, as an object (http.IncomingMessage object).

This object has a property called "url" which holds the part of the url that comes after the domain name:

http://localhost:8080/summer http://localhost:8080/winter
Node.js HTTP Module
Split the Query String
There are built-in modules to easily split the query string into readable parts, such as the URL module.
Node.js HTTP Module
Split the Query String
Node.js File System Module
Node.js File System Module
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');
Node.js File System Module
Node.js as a File Server
Common use for the File System module:

● Read files
● Create files
● Update files
● Delete files
● Rename files
Node.js File System Module
Read Files

The fs.readFile() method is used to read files on your computer.

Assume we have the following HTML file (located in the same folder as Node.js):

demofile1.html

<html>

<body>

<h1>My Header </h1>

<p>My paragraph. </p>

</body>

</html>
Node.js File System Module
Read Files
Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
}); http://localhost:8080
}).listen(8080);
Node.js File System Module
Create Files
The File System module has methods for creating new files:

● fs.appendFile()
● fs.open()
● fs.writeFile()

The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be
created:
Node.js File System Module
Create Files
Node.js File System Module
Create Files
Node.js File System Module
Create Files
Node.js File System Module
Update Files
The File System module has methods for updating files:

● fs.appendFile()
● fs.writeFile()

The fs.appendFile() method appends the specified content at the end of the specified file:
Node.js File System Module
Update Files
Node.js File System Module
Update Files
Node.js File System Module
Delete Files
Node.js File System Module
Rename Files
To rename a file with the File System module, use the fs.rename() method.

The fs.rename() method renames the specified file:


Node.js URL Module
Node.js URL Module
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');

Parse an address with the url.parse() method, and it will return a URL object with each part of the address as
properties:
Node.js URL Module
Node.js URL Module
Node.js File Server
Create two html files and save them in the same folder as your node.js files
Node.js URL Module
Node.js File Server

Create a Node.js file that opens the requested file and returns the content to the client. If anything goes wrong,
throw a 404 error:
Node.js URL Module
Node.js File Server

http://localhost:8080/winter.html

http://localhost:8080/summer.html
Node.js NPM
What is NPM?
NPM is a package manager for Node.js packages, or modules if you like.

www.npmjs.com hosts thousands of free packages to download and use.

The NPM program is installed on your computer when you install Node.js

NPM is already ready to run on your computer!


Node.js URL Module
What is NPM?
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":


Node.js URL Module
Download
Node.js URL Module
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:
Node.js URL Module
Using a Package
Example
var http = require('http');

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

http.createServer(function (req, res) {

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

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

res.end();

}).listen(8080);
Node.js URL Module
Using a Package
Node.js Events
Events in Node.js

Node.js is perfect for event-driven applications.

Every action on a computer is an event. Like when a connection is made or a file is opened.

Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file:
Node.js Events
Events in Node.js
Example
var fs = require('fs');

var rs = fs.createReadStream('./demofile.txt');

rs.on('open', function () {

console.log('The file is open');

});
Node.js Events
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();


Node.js Events
The EventEmitter Object
You can assign event handlers to your own events with the EventEmitter object.

In the example below we have created a function that will be executed when a "scream" event is fired.

To fire an event, use the emit() method.


Node.js Events
Node.js Upload Files
The Formidable Module
There is a very good module for working with file uploads, called "Formidable".

The Formidable module can be downloaded and installed using NPM:

C:\Users\Your Name>npm install formidable

After you have downloaded the Formidable module, you can include the module in any application:

var formidable = require('formidable');


Node.js Upload Files
Upload Files
Now you are ready to make a web page in Node.js that lets the user upload files to your computer:

Step 1: Create an Upload Form


Create a Node.js file that writes an HTML form, with an upload field:
Node.js Upload Files
Example
Node.js Upload Files
Step 2: Parse the Uploaded File
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.
Node.js Upload Files
Node.js Upload Files
Step 3: Save the File
When a file is successfully uploaded to the server, it is placed on a temporary folder.

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

To move the file to the folder of your choice, use the File System module, and rename the file:
Node.js Upload Files
Node.js Send an Email
The Nodemailer Module
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

After you have downloaded the Nodemailer module, you can include the module in any application:

var nodemailer = require('nodemailer');


Node.js Send an Email
Send an Email
Now you are ready to send emails from your server.

Use the username and password from your selected email provider to send an email. This tutorial will show you
how to use your Gmail account to send an email:
Node.js Send
an Email

Example
Node.js Send
an Email
Node.js Send an Email
Reference
https://www.w3schools.com/nodejs/default.asp

https://youtu.be/f2EqECiTBL8?si=4DxG7s93Ow1YVYoC

You might also like