0% found this document useful (0 votes)
8 views33 pages

Uit FSWD Unit2

Node.js is an open-source, cross-platform server environment that uses JavaScript for server-side programming, allowing for non-blocking, asynchronous operations. It can handle tasks such as generating dynamic content, managing files, and interacting with databases, while also supporting the creation of custom modules and the use of built-in modules like HTTP and File System. Additionally, Node.js includes a package manager called NPM for managing libraries and packages, making it easy to extend its functionality.
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)
8 views33 pages

Uit FSWD Unit2

Node.js is an open-source, cross-platform server environment that uses JavaScript for server-side programming, allowing for non-blocking, asynchronous operations. It can handle tasks such as generating dynamic content, managing files, and interacting with databases, while also supporting the creation of custom modules and the use of built-in modules like HTTP and File System. Additionally, Node.js includes a package manager called NPM for managing libraries and packages, making it easy to extend its functionality.
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/ 33

lOMoARcPSD|45310002

lOMoARcPSD|45310002

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

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:

1. Sends the task to the computer's file system.


2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Here is how Node.js handles a file request:

1. Sends the task to the computer's file system.


2. Ready to handle the next request.
3. 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.
lOMoARcPSD|45310002

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"
lOMoARcPSD|45310002

Now, your computer works as a server!

If anyone tries to access your computer on port 8080, they will get a "Hello World!" message in
return!

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

Installing Node.js
• To easily install Node.js, download an installer from the Node.js website at
http://nodejs.org.
• The Node.js installer installs the necessary files on your PC to get Node.js up and
running.
• No additional configuration is necessary to start creating Node.js applications.

Looking at the Node.js Install Location


• If you look at the install location, you will see a couple of executable files and a
node_modules folder.
• The node executable file starts the Node.js JavaScript VM.
• The following list describes the executables in the Node.js install location that you
need to get started:
o node:
▪ This file starts a Node.js JavaScript VM.
▪ If you pass in a JavaScript file location, Node.js executes that script.
▪ If no target JavaScript file is specified, then a script prompt is shown
that allows you to execute JavaScript code directly from the console.
o npm:
▪ This command is used to manage the Node.js packages
lOMoARcPSD|45310002

o node_modules:
▪ This folder contains the installed Node.js packages.
▪ These packages act as libraries that extend the capabilities of
Node.js.

Verify Node.js Executables


lOMoARcPSD|45310002

Ex2:
lOMoARcPSD|45310002

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.

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 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:

Save the code above in a file called "myfirst.js", and initiate the file:
lOMoARcPSD|45310002

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

The function passed into the http.createServer() method, will be executed when someone
tries to access the computer on port 8080.

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:

Ex2:
lOMoARcPSD|45310002

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.

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:
lOMoARcPSD|45310002

Split the Query String


There are built-in modules to easily split the query string into readable parts, such as the
URL module.

Split the query string into readable parts:

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

http://localhost:8080/?year1=2024&month1=august

http://localhost:8080/?year1=2024&month2=august

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

Include 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:

Use the exports keyword to make properties and methods available outside the module file.

Save the code above in a file called "usermod.js"

Include Your Own Module


Now you can include and use the module in any of your Node.js files.
lOMoARcPSD|45310002

Notice that we use ./ to locate the module, that means that the module is located in the
same folder as the Node.js file.

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

http://localhost:8080

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');
Common use for the File System module:
• Read files
• Create files
• Update files
• Delete files
• Rename files

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):
a1.html
lOMoARcPSD|45310002

Create a Node.js file that reads the HTML file, and return the content:
Example Get your own Node.js Server
lOMoARcPSD|45310002
lOMoARcPSD|45310002

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:

Create a new file using the appendFile() method:


var fs = require('fs');

The fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the
specified file is opened for writing. If the file does not exist, an empty file is created:
Create a new, empty file using the open() method:
lOMoARcPSD|45310002

The fs.writeFile() method replaces the specified file and content if it exists. If the file does not
exist, a new file, containing the specified content, will be created:

Example
Create a new file using the writeFile() method:
lOMoARcPSD|45310002

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:

the fs.writeFile() method replaces the specified file and content:


lOMoARcPSD|45310002

Delete Files
To delete a file with the File System module, use the fs.unlink() method.
The fs.unlink() method deletes the specified file:

Rename Files
To rename a file with the File System module, use the fs.rename() method.
The fs.rename() method renames the specified file:
lOMoARcPSD|45310002
lOMoARcPSD|45310002

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:
lOMoARcPSD|45310002

Node.js File Server


Now we know how to parse the query string, and in the previous chapter we learned how
to make Node.js behave as a file server. Let us combine the two, and serve the file requested by
the client.

Create a Node.js file that opens the requested file and returns the content to the client.
lOMoARcPSD|45310002
lOMoARcPSD|45310002

If anything goes wrong, throw a 404 error:

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!

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":
lOMoARcPSD|45310002

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
lOMoARcPSD|45310002

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:
ExampleGet your own Node.js Server
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);

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
lOMoARcPSD|45310002

2.5 CREATING A SIMPLE NODEJS APPLICATION

Console.log Example::
lOMoARcPSD|45310002

Console.info Example:

Console.error Example:

Console.warn Example:
lOMoARcPSD|45310002
lOMoARcPSD|45310002
lOMoARcPSD|45310002

2.8 timers

1. setTimeout( )

Example 2:

setImmediate( ) Function::

Syntax :

setImmediate( ( ) =>{ // function body }; )


lOMoARcPSD|45310002

2.9 callbacks
lOMoARcPSD|45310002

2.10 BUFFERS

• It is class that allows us to store raw data similar to arrays.


• A class that provides instances for storing the data.
• It’s a global class so we can use it without any need of importing a buffer module.

Creation of buffer

➢ Simple .
➢ Example : var buff = new Buffer(10);
lOMoARcPSD|45310002

You might also like