NODE.
JS
BASIC
TUTORIAL
LECTURER: NGUYEN MINH DAO
2
[Link]
INTRODUCTI
ON
NGUYEN MINH DAO
WHAT IS [Link]?
• [Link] is an open source server environment
• [Link] is free
• [Link] runs on various platforms (Windows, Linux, Unix,
Mac OS X, etc.)
• [Link] uses JavaScript on the server
NGUYEN MINH DAO 3
WHY [Link]?
[Link] 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:
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.
NGUYEN MINH DAO 4
WHY [Link]?
Here is how [Link] 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.
[Link] eliminates the waiting, and simply continues with the next request.
[Link] runs single-threaded, non-blocking, asynchronously programming,
which is very memory efficient.
NGUYEN MINH DAO 5
WHAT CAN [Link] DO?
• [Link] can generate dynamic page content
• [Link] can create, open, read, write, delete, and close files
on the server
• [Link] can collect form data
• [Link] can add, delete, modify data in your database
NGUYEN MINH DAO 6
WHAT IS A [Link] FILE?
• [Link] files contain tasks that will be executed on certain
events
• A typical event is someone trying to access a port on the
server
• [Link] files must be initiated on the server before having
any effect
• [Link] files have extension ".js"
NGUYEN MINH DAO 7
8
[Link]
GET
STARTED
NGUYEN MINH DAO
EXAMPLE – [Link] HTTP
SERVER
Create a basic HTTP server listening on a port.
Use any text editor of your choice to create a script file
with extension .js .
Create a file with the name [Link] and copy
the following content to it.
NGUYEN MINH DAO 9
EXAMPLE – [Link] HTTP
SERVER
NGUYEN MINH DAO 10
EXAMPLE – [Link] HTTP
SERVER
NGUYEN MINH DAO 11
EXAMPLE – [Link] HTTP
SERVER
NGUYEN MINH DAO 12
[Link] COMMAND LINE
ARGUMENTS – EXAMPLE
Example 1 – Read Arguments from Command Line
NGUYEN MINH DAO 13
[Link] COMMAND LINE
ARGUMENTS – EXAMPLE
NGUYEN MINH DAO 14
15
[Link]
MODULES
NGUYEN MINH DAO
MODULES IN [Link]
A [Link] Module is a library of functions that could be used in a
[Link] file.
NGUYEN MINH DAO 16
MODULES IN [Link]
There are three types of modules in [Link] based on their location to
access.
Built-in Modules
These are the modules that come along with [Link] installation.
User defined Modules
These are the modules written by user or a third party.
Third party Modules
There are many modules available online which could be used in [Link].
Node Package Manager (NPM) helps to install those modules, extend them if
necessary and publish them to repositories like Github for access to distributed
machines.
NGUYEN MINH DAO 17
INCLUDE A MODULE
Including a module in the [Link] files allows us to use the
functions exposed by the module.
Syntax
Following is the syntax to include a module in a [Link] file.
NGUYEN MINH DAO 18
INCLUDE A MODULE
Example
To include ‘http’ module in a [Link] file, we need to write the
below require statement before using the http module.
NGUYEN MINH DAO 19
USING FUNCTION OF A
MODULE
Once you have included a module by assigning it to a variable, the
functions in the module could be accessed through the variable.
In the above module section, an example for including http module
is provided.
Now we shall use a function of http module called createServer()
to demonstrate on how to use a function of a module.
NGUYEN MINH DAO 20
USING FUNCTION OF A
MODULE
The function creates an HTTP Server that responds with ‘[Link] says
Hello!’ when an http request is made to port 8080.
NGUYEN MINH DAO 21
22
HOW TO
CREATE A
[Link]
MODULE
NGUYEN MINH DAO
CREATE MODULE IN
[Link]
Most of the necessary functions are included in the Built-in
Modules.
Sometimes it is required that, when you are implementing a [Link]
application for a use case, you might want to keep your business
logic separately.
In such cases you create a [Link] module with all the required
functions in it.
NGUYEN MINH DAO 23
CREATE MODULE IN
[Link]
NGUYEN MINH DAO 24
HOW TO CREATE A [Link]
MODULE?
A [Link] Module is a .js file with one or more functions.
The syntax to define a function in [Link] module is
exports – is a keyword which tells [Link] that the function is available outside the
module.
function_name – is the function name using which we can access this function in
other programs.
NGUYEN MINH DAO 25
CALCULATOR –
EXAMPLE
[Link] MODULE
Following is an example
where we create a
Calculator [Link]
Module with functions
add, subtract and
multiply.
And use the Calculator
module in another
[Link] file.
NGUYEN MINH DAO 26
CALCULATOR –
EXAMPLE
[Link] MODULE
Following is an example
where we create a
Calculator [Link]
Module with functions
add, subtract and
multiply.
And use the Calculator
module in another
[Link] file.
NGUYEN MINH DAO 27
28
EXTEND OR
ADD
FUNCTIONS TO
[Link]
MODULE
NGUYEN MINH DAO
EXTEND OR ADD
FUNCTIONS TO [Link]
MODULE
To add a new function to a [Link] module, following is a step-by-
step guide.
1. Include the module
The first step to extend a module is to include the module itself using require
function
var newMod = require('<module_name>');
We have retrieved the module to a variable.
NGUYEN MINH DAO 29
EXTEND OR ADD
FUNCTIONS TO [Link]
MODULE
2. Add function to the module variable
Using variable to the module, newMod , add a new function to it
using following syntax.
newMod.<newFunctionName> = function(function_parameters) {
// function body
};
You may add as many number of new functions to the module as per
your requirement. Any modifications to the module variable does not
affect the actual module in its original form.
NGUYEN MINH DAO 30
EXTEND OR ADD
FUNCTIONS TO [Link]
MODULE
3. Re-export the module
You have to re-export the module for the new added functionalities to
take effect.
[Link] = newMod;
Now, you may use the variable to the module, newMod , for calling
new functionalities added.
NGUYEN MINH DAO 31
EXAMPLE : EXTEND OR ADD
FUNCTIONS TO [Link]
MODULE In this example we shall add a new function,
printMessage() to Node fs module.
NGUYEN MINH DAO 32
EXTEND OR ADD
FUNCTIONS TO [Link]
MODULE
Step 4: Re-export the module.
You have to re-export the module for the overridden functionalities to
take effect.
Now, you may use the variable to the module, newMod , for calling
the function, and the overridden functionality would be executed.
NGUYEN MINH DAO 33
EXAMPLE 1 – OVERRIDE FUNCTION OF A
[Link] MODULE
In this example, we shall override readFile() function of Node fs module.
Overriding readFile() function may not be a great idea, but would suffice for
demonstration.
NGUYEN MINH DAO 34
35
[Link]
CALLBACK
FUNCTION
NGUYEN MINH DAO
[Link] CALLBACK
FUNCTION
[Link] Callback Function : Asynchronism is one of the
fundamental factor for [Link] to have become popular. And Callback
is the realization of asynchronism for functions. Generally, in [Link],
most of the functions that work on resources have callback variants.
When an asynchronous function is called upon a resource for some
task, the control is let immediately to continue with the subsequent
statements after the function. The task on the resource would start in
parallel.
NGUYEN MINH DAO 36
[Link] CALLBACK
FUNCTION
This helps [Link] continue with other tasks while the function is
working with the resource. Once the task with the resource is
completed, [Link] resumes with the callback function.
Callback function is called with arguments : data object, result
object and (or) error object containing information regarding the
task.
NGUYEN MINH DAO 37
BLOCKING FUNCTION
Blocking Function: In contrast to asynchronous function, a
synchronous function blocks the execution until the task on the
resource is completed. Therefore, synchronous function is also
called as blocking function.
[Link] Nested Callback Function: If there are multiple
operations to be done on the resource sequentially, and also has to
be done asynchronously, you may nest the callback functions, one
in another.
NGUYEN MINH DAO 38
EXAMPLE 1 – BLOCKING
FUNCTION
In this example, we will read a file “[Link]” synchronously
using readFileSync() method.
NGUYEN MINH DAO 39
EXAMPLE 1 – BLOCKING
FUNCTION
The after readFileSync statement is always executed only after
reading the file is completed.
[Link] is blocking the execution flow.
NGUYEN MINH DAO 40
EXAMPLE 2 – [Link]
CALLBACK FUNCTION
Following is an example node script which reads “[Link]” file
asynchronously, with the help of [Link] Callback Function.
NGUYEN MINH DAO 41
EXAMPLE 2 – [Link]
CALLBACK FUNCTION
Run this program using node in command-prompt/terminal, and
you will get the following output.
NGUYEN MINH DAO 42
EXAMPLE 2 – [Link]
CALLBACK FUNCTION
You may observe that even after executing [Link](“After
readFile asynchronously:.”); statement, it took around 5ms to
complete reading the file.
[Link](‘[Link]’, callback function{..}) has not blocked the
execution, instead a new process is started in parallel with the main
control flow, to read the file (perform the task on resource).
NGUYEN MINH DAO 43
EXAMPLE 3 – [Link] NESTED
CALLBACK FUNCTION
To demonstrate [Link] Nested
Callback Function, we shall
consider a scenario of renaming a
file and then deleting it using
asynchronous functions.
NGUYEN MINH DAO 44
EXAMPLE 3 – [Link] NESTED
CALLBACK FUNCTION
Run this program using node in command-prompt/terminal, and you will
get the following output.
Output
NGUYEN MINH DAO 45
46
[Link]
FOREACH
NGUYEN MINH DAO
[Link] FOREACH
[Link] forEach is used to execute the provided function for each
element. The syntax of forEach is;
myFunction function is executed for each element in arr. The
element of array is passed as argument to the function during each
iteration.
NGUYEN MINH DAO 47
EXAMPLE 1 – FOREACH ON
ARRAY OF ELEMENTS
In this example, we will use forEach to apply on each element of
array.
NGUYEN MINH DAO 48
EXAMPLE 2 – FOREACH ON ARRAY OF
ELEMENTS WITH EXTERNAL
FUNCTION PASSED AS ARGUMENT
NGUYEN MINH DAO 49
EXAMPLE 3: FOREACH ON ARRAY WITH
ACCESS TO ELEMENT, INDEX AND ARRAY
NGUYEN MINH DAO 50
51
[Link]
HTTP
MODULE
NGUYEN MINH DAO
THE BUILT-IN HTTP
MODULE
[Link] has a built-in module called HTTP, which allows
[Link] to transfer data over the Hyper Text Transfer
Protocol (HTTP).
To include the HTTP module, use the require() method:
var http = require('http’);
NGUYEN MINH DAO 52
[Link] 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:
NGUYEN MINH DAO 53
ADD AN HTTP HEADER
NGUYEN MINH DAO 54
READ THE QUERY STRING
The function passed into the [Link]() has a req argument that
represents the request from the client, as an object
([Link] object).
This object has a property called "url" which holds the part of the url
that comes after the domain name:
NGUYEN MINH DAO 55
SPLIT THE QUERY STRING
NGUYEN MINH DAO 56
57
[Link]
FILE
SYSTEM
MODULE
NGUYEN MINH DAO
[Link] AS A FILE SERVER
The [Link] 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
NGUYEN MINH DAO 58
READ FILES
The [Link]() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as
[Link]):
NGUYEN MINH DAO 59
READ FILES
Create a [Link] file that reads the HTML file, and return the content:
NGUYEN MINH DAO 60
CREATE FILES
The File System module has methods for creating new files:
[Link]()
[Link]()
[Link]()
The [Link]() method appends specified content to a file. If the file does
not exist, the file will be created:
NGUYEN MINH DAO 61
CREATE FILES
NGUYEN MINH DAO 62
CREATE FILES
The [Link]() 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:
NGUYEN MINH DAO 63
CREATE FILES
NGUYEN MINH DAO 64
CREATE FILES
The [Link]() 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:
NGUYEN MINH DAO 65
CREATE FILES
NGUYEN MINH DAO 66
UPDATE FILES
The File System module has methods for updating files:
[Link]()
[Link]()
The [Link]() method appends the specified content at the end of the specified file.
Append "This is my text." to the end of the file "[Link]":
NGUYEN MINH DAO 67
UPDATE FILES
The [Link]() method replaces the specified file and content:
Example
Replace the content of the file "[Link]":
NGUYEN MINH DAO 68
DELETE FILES
To delete a file with the File System module, use the [Link]() method. The
[Link]() method deletes the specified file.
Example
Delete "[Link]":
NGUYEN MINH DAO 69
RENAME FILES
To rename a file with the File System module, use the [Link]() method.
The [Link]() method renames the specified file.
Example
Rename "[Link]" to "[Link]":
NGUYEN MINH DAO 70
RENAME FILES
NGUYEN MINH DAO 71
72
[Link]
URL
MODULE
NGUYEN MINH DAO
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 [Link]() method, and it will return a
URL object with each part of the address as properties
NGUYEN MINH DAO 73
THE BUILT-IN URL MODULE
NGUYEN MINH DAO 74
[Link] FILE SERVER
Now we know how to parse the query string, and in the previous chapter we
learned how to make [Link] behave as a file server. Let us combine the two,
and serve the file requested by the client.
Create two html files and save them in the same folder as your [Link] files.
NGUYEN MINH DAO 75
[Link] FILE SERVER
NGUYEN MINH DAO 76
NGUYEN MINH DAO 77
78
[Link]
NPM
NGUYEN MINH DAO
WHAT IS NPM?
NPM is a package manager for [Link] packages, or modules if
you like.
[Link] hosts thousands of free packages to download
and use.
The NPM program is installed on your computer when you install
[Link]
NPM is already ready to run on your computer!
NGUYEN MINH DAO 79
WHAT IS A PACKAGE?
A package in [Link] 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.
NGUYEN MINH DAO 80
WHAT IS A PACKAGE?
I want to download a package called "upper-case":
Download "upper-case":
C:\Users\Your Name>npm install upper-case
NGUYEN MINH DAO 81
WHAT IS A PACKAGE?
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
NGUYEN MINH DAO 82
NGUYEN MINH DAO 83
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 [Link] file that will convert the output "Hello World!" into upper-case
letters:
NGUYEN MINH DAO 84
USING A PACKAGE
NGUYEN MINH DAO 85
86
[Link]
EVENTS
NGUYEN MINH DAO
EVENTS IN [Link]
Every action on a computer is an event. Like when a connection is made or a
file is opened.
Objects in [Link] can fire events, like the readStream object fires events
when opening and closing a file:
NGUYEN MINH DAO 87
EVENTS MODULE
[Link] 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 [Link]();
NGUYEN MINH DAO 88
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.
NGUYEN MINH DAO 89
NGUYEN MINH DAO 90
NGUYEN MINH DAO 91