Node-Mongo-RestAPI
Node-Mongo-RestAPI
js
Node.js Introduction
Introduction
Hello and welcome to our backend track. In this track we are going to learn how to
create a backend server using Node.js, Express and MongoDB. These are the
technologies that we are going to use during this track.
Let’s start with Node.js. In this Super Skill, we are going to:
What is Node.js?
Node.js is a server-side platform built on Google Chrome's JavaScript
Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009. The
definition of Node.js as supplied by its official documentation is as follows:
Concepts
The following diagram depicts some important parts of Node.js which we
will discuss in detail in the subsequent chapters.
Assessment: Quiz
What are the correct answers?
Node.js is a web framework (like Rails or Django, though it can be used to make
similar things). Node.js is a JavaScript runtime environment. A programming
language.
Who developed NodeJS?
Environment Setup
Local Environment Setup
To set up your environment for Node.js, you need the following two
softwares available on your computer (a) Text Editor and (b)
The Node.js binary installables.
Text Editor
This will be used to type your program. Examples of few editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi,
... or simply VSCode.
The name and version of the text editor can vary on different operating
systems. For example, Notepad will be used on Windows, and vim or vi
can be used on windows as well as Linux or UNIX.
The files you create with your editor are called source files and contain
program source code. The source files for Node.js programs are typically
named with the extension ".js".
Before starting your programming, make sure you have one text editor in
place and you have enough experience to write a computer program, save
it in a file, and finally execute it.
The following section will guide you on how to install Node.js binary
distribution on various OS.
Download Node.js
Download latest version LTS (Long Term Support) of Node.js installable
archive file from Node.js Downloads
Installation on UNIX/Linux/Mac OS X,
and SunOS
Based on your OS architecture, download and extract the archive node-
vx.x.x-osname.tar.gz into /tmp, and then finally move the extracted files
into /usr/local/nodejs directory. For example:
$ cd /tmp
$ wget http://nodejs.org/dist/v11.3.1/node-v11.3.1-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v11.3.1-linux-x64/* /usr/local/nodejs
OS Output
Linux export
PATH=$PATH:/usr/local/nodejs/bin
Mac export
PATH=$PATH:/usr/local/nodejs/bin
FreeBS export
D PATH=$PATH:/usr/local/nodejs/bin
Installation on Windows
Use the MSI file and follow the prompts to install the Node.js. By default,
the installer uses the Node.js distribution in C:\Program Files\nodejs. The
installer should set the C:\Program Files\nodejs\bin directory in window's
PATH environment variable. Restart any open command prompts for the
change to take effect.
Verify installation
To verify that Node.js is installed in your machine just run the following
command:
node -v
Executing a File
Create a js file named main.js on your machine (Windows or Linux)
having the following code.
/* Hello, World! program in node.js */
console.log("Hello, World!")
Now execute main.js file using Node.js interpreter to see the result:
$ node main.js
If everything is fine with your installation, this should produce the following
result:
Hello, World!
Assessment: Quiz
How can I check if node is installed?
True False
First Application
First Application
Before creating an actual "Hello, World!" application using Node.js, let us
see the components of a Node.js application. A Node.js application
consists of the following three important components:
response.end('Hello World\n');
}).listen(8081);
The above code is enough to create an HTTP server which listens, i.e.,
waits for a request over 8081 port on the local machine.
Local modules are modules created locally in your Node.js application. Local
modules are part of Node.js modules.
To import a Node module, we use the keyword:
True False
REPL Terminal
Starting REPL
REPL stands for Read Eval Print Loop and it represents a computer
environment like a Windows console or Unix/Linux shell where a command
is entered and the system responds with an output in an interactive mode.
Node.js or Node comes bundled with a REPL environment. It performs the
following tasks:
Read − Reads user's input, parses the input into JavaScript data-
structure, and stores it into memory.
Eval − Takes and evaluates the data structure.
Print − Prints the result.
Loop − Loops the above command until the user presses ctrl-
c twice.
The REPL feature of Node is very useful in experimenting with Node.js
codes and debugging JavaScript codes.
You will see the REPL Command prompt > where you can type any Node.js
command.
$ node
>
Simple Expression
Let's try some simple mathematics with the Node.js REPL command
prompt:
$ node
> 1 + 3
> 1 + ( 2 * 3 ) - 4
>
Use Variables
You can use variables to store values and print them later like any
conventional script. If var keyword is not used, then the value is stored in
the variable and printed. Whereas if var keyword is used, then the value is
stored but not printed. You can print variables using console.log().
$ node
> x = 10
10
> var y = 10
undefined
> x + y
20
Hello World
undefined
Multiline Expression
Node REPL supports multiline expression similar to JavaScript. Let's check
the following do-while loop in action.
$ node
> var x = 0
undefined
> do {
... x++;
... }
while ( x < 5 );
x: 1
x: 2
x: 3
x: 4
x: 5
undefined
>
... comes automatically when you press Enter after the opening bracket.
Node automatically checks the continuity of expressions.
Underscore Variable
You can use underscore (_) to get the last result
$ node
> var x = 10
undefined
> var y = 20
undefined
> x + y
30
undefined
> console.log(sum)
30
undefined
>
REPL Commands
ctrl + c − terminates the current command.
ctrl + c twice − terminates the Node REPL.
ctrl + d − terminates the Node REPL.
Up/Down Keys − see command history and modify previous
commands.
tab Keys − list all of the current commands.
.help − list all of the commands.
.break − exits from multiline expression.
.clear − exits from multiline expression.
.save filename − saves the current Node REPL session to a file.
.load filename − loads file content from current Node REPL
session.
Stopping REPL
As mentioned above, you will need to use ctrl-c twice to come out of
Node.js REPL.
$ node
>
>
Fill in the blanks Solution
ctrl + c : terminates the current command. ctrl + d : terminates the Node REPL. tab
Keys : list all of the current commands. .break : exits from multiline expression. .save
filename : saves the current Node REPL session to a file. ctrl + c twice : terminates
the Node REPL. Up/Down Keys : see command history and modify previous
commands. .help : lists all of the commands. .clear : exits from multiline
expression. .load filename : loads file content from current Node REPL session.
NPM comes bundled with Node.js installables after v0.6.3 version. To verify
the version, open the console and type the following command and see
the result:
$ npm --version
6.13.4
If you are running an old version of NPM then it is quite easy to update it
to the latest version. Just use the following command from root:
$ npm install npm -g
For example, the following is the command to install a famous Node.js web
framework module called Express:
$ npm install express
Now you can use this module in your .js file as follows:
var express = require('express');
total 0
Alternatively, you can use npm ls command to list down all the locally
installed modules.
This will produce a similar result but the module will be installed globally.
Here, the first line shows the module version and the location where it is
getting installed.
[email protected] /usr/lib/node_modules/express
├── [email protected]
├── [email protected]
You can use the following command to check all the modules that were
globally installed:
$ npm ls -g
Using package.json
package.jsonis present in the root directory of any Node
application/module and is used to define the properties of a package. Let's
open package.json from the express package present
in node_modules/express/
{
"name": "express",
"version": "4.11.2",
"author": {
"email": "[email protected]"
},
"contributors": [{
"name": "Aaron Heckmann",
"email": "[email protected]"
},
"email": "[email protected]"
},
"email": "[email protected]"
},
"email": "[email protected]"
},
"email": "[email protected]"
},
"email": "[email protected]"
},
{
"email": "[email protected]"
} ],
"type": "git",
"url": "https://github.com/strongloop/express"
},
"express",
"framework",
"sinatra",
"web",
"rest",
"restful",
"router",
"app",
"api"
],
"dependencies": {
"accepts": "~1.2.3",
"content-disposition": "0.5.0",
"cookie-signature": "1.0.5",
"debug": "~2.1.1",
"depd": "~1.0.0",
"escape-html": "1.0.1",
"etag": "~1.5.1",
"finalhandler": "0.3.3",
"fresh": "0.2.4",
"media-typer": "0.3.0",
"methods": "~1.1.1",
"on-finished": "~2.2.0",
"parseurl": "~1.3.0",
"path-to-regexp": "0.1.3",
"proxy-addr": "~1.0.6",
"qs": "2.3.3",
"range-parser": "~1.0.2",
"send": "0.11.1",
"serve-static": "~1.8.1",
"type-is": "~1.5.6",
"vary": "~1.0.0",
"cookie": "0.1.2",
"merge-descriptors": "0.0.2",
"utils-merge": "1.0.0"
},
"devDependencies": {
"after": "0.8.1",
"ejs": "2.1.4",
"istanbul": "0.3.5",
"marked": "0.3.3",
"mocha": "~2.1.0",
"should": "~4.6.2",
"supertest": "~0.15.0",
"hjs": "~0.0.6",
"body-parser": "~1.11.0",
"connect-redis": "~2.2.0",
"cookie-parser": "~1.3.3",
"express-session": "~1.10.2",
"jade": "~1.9.1",
"method-override": "~2.3.1",
"morgan": "~1.5.1",
"multiparty": "~4.1.1",
"vhost": "~3.0.0"
},
"engines": {
},
"files": [
"LICENSE",
"History.md",
"Readme.md",
"index.js",
"lib/"
],
"scripts": {
},
"gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada",
"bugs": {
"url": "https://github.com/strongloop/express/issues"
},
"_id": "[email protected]",
"_shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"_from": "express@*",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "[email protected]"
},
"maintainers": [{
"name": "tjholowaychuk",
"email": "[email protected]"
},
"name": "jongleberry",
"email": "[email protected]"
},
{
"name": "shtylman",
"email": "[email protected]"
},
"name": "dougwilson",
"email": "[email protected]"
},
"name": "aredridel",
"email": "[email protected]"
},
"name": "strongloop",
"email": "[email protected]"
},
"name": "rfeng",
"email": "[email protected]"
}],
"dist": {
"shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"tarball": "https://registry.npmjs.org/express/-/express-
4.11.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/express/-/express-
4.11.2.tgz",
Attributes of Package.json
Demystified
name − the name of the package
version − the version of the package
description − the description of the package
homepage − the homepage of the package
author − the author of the package
contributors − the name of the contributors to the package
dependencies − the list of dependencies. NPM automatically
installs all the dependencies mentioned here in the node_module
package folder.
repository − the repository type and the URL of the package.
main − the package entry point.
keywords − keywords.
Uninstalling a Module
Use the following command to uninstall a Node.js module.
$ npm uninstall express
Once NPM uninstalls the package, you can verify it by looking at the
content of /node_modules/ directory or type the following command −
$ npm ls
Updating a Module
Update package.json and change the version of the dependency to be
updated and run the following command.
$ npm update express
Search a Module
Search a package name using NPM.
$ npm search express
Create a Module
Creating a module requires package.json to be generated. Let's generate
package.json using npm init, which will generate the basic skeleton of the
package.json.
$ npm init
This utility will walk you through the creation of a package.json file.
It only covers the most common items, and tries to guess sane defaults.
name: (webmaster)
You will need to provide all the required information about your module.
You can take help from the above-mentioned package.json file to
understand the meanings of various information demanded. Once
package.json is generated, use the following command to register yourself
with NPM repository site using a valid email address.
$ npm adduser
Username: randomname
Password:
Assessment: Quiz
What is the difference between core modules and third party modules?
The first one is installed separately and the second one is installed with Node.js.
The first one is installed with nodejs and the second must be installed separately.
What does npm init do?
Create a node folder. Initialize a node project with package.json file. Install
a module called init.
To install a package using npm, we run:
Callbacks Concept
What is Callback?
Callback is an asynchronous equivalent of a function. A callback function is
called at the completion of a given task. Node makes heavy use of
callbacks. All the Node APIs are written in such a way that they support
callbacks.
For example, a file reading function may start reading files and return
control to the execution environment immediately so that the next
instruction can be executed. Once file I/O is complete, it will call the
callback function while passing the callback function, the content of the
file as a parameter. So there is no blocking or wait for File I/O. This makes
Node.js highly scalable as it can process a high number of requests
without waiting for any function to return results.
console.log(data.toString());
console.log("Program Ended");
Program Ended
console.log(data.toString());
});
console.log("Program Ended");
The first example shows that the program blocks the call until it
reads the file and only then it proceeds to end the program.
The second example shows that the program does not wait for file
reading and proceeds to print "Program Ended" and at the same
time, the program, without blocking, continues reading the file.
Assessment: Quiz
Node.js is a single-threaded application, but it can support concurrency with the
concept of events and callbacks.
True False
The blocking code approach means that the execution will stop until that part of code
finishes executing.
True False
Callbacks are the solution for handling asynchronous events.
True False
Event Loop
Node.js - Event Loop
Node.js is a single-threaded application, but it can support concurrency
via the concept of event and callbacks. Every Node.js API is
asynchronous and being single-threaded, they use async function
calls to maintain concurrency. Node uses observer patterns. Node thread
keeps an event loop and whenever a task gets completed, it fires the
corresponding event which signals the event-listener function to execute.
Event-Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is
pretty fast compared to other similar technologies. As soon as Node starts
its server, it simply initiates its variables, declares functions and then
simply waits for the event to occur.
Event Loop
Although events look quite similar to callbacks, the difference lies in the fact that
callback functions are called when an asynchronous function returns its result,
whereas event handling works on the observer pattern. The functions that listen
to events act as Observers. Whenever an event gets fired, its listener function
starts executing. Node.js has multiple built-in events available through events
module and EventEmitter classes which are used to bind events and event-
listeners as follows:
The following is the syntax to bind an event handler with another event:
// Bind event and event handler as follows
eventEmitter.on('eventName', eventHandler);
eventEmitter.emit('eventName');
Example
Create a .js file named main.js with the following code:
// Import events module
console.log('connection succesful.');
eventEmitter.emit('data_received');
eventEmitter.on('connection', connectHandler);
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function() {
});
eventEmitter.emit('connection');
console.log("Program Ended.");
Now let's try to run the above program and check its output:
$ node main.js
Program Ended.
if (err) {
console.log(err.stack);
return;
}
console.log(data.toString());
});
console.log("Program Ended");
Event Emitter
EventEmitter Class
Many objects in a Node emit events, for example, a net.Server emits an
event each time a peer connects to it. An fs.readStream emits an event
when the file is opened. All objects which emit events are the instances of
events.EventEmitter.
Methods
addListener(event, listener) : Adds a listener at the end of the
listeners array for the specified event. No checks are made to see if
the listener has already been added. Multiple calls passing the same
combination of event and listener will result in the listener being
added multiple times. Returns emitter, so calls can be chained.
on(event, listener) : Adds a listener at the end of the listeners
array for the specified event. No checks are made to see if the
listener has already been added. Multiple calls passing the same
combination of event and listener will result in the listener being
added multiple times. Returns emitter, so calls can be chained.
once(event, listener) : Adds a one time listener to the event. This
listener is invoked only the next time an event is fired, after which it
is removed. Returns emitter, so calls can be chained.
removeListener(event, listener) : Removes a listener from the
listener array for the specified event. Caution − It changes the array
indices in the listener array behind the listener. removeListener will
remove, in most occasions, one instance of a listener from the
listener array. If any single listener has been added multiple times to
the listener array for the specified event, then removeListener must
be called multiple times to remove each instance. Returns emitter,
so calls can be chained.
removeAllListeners([event]) : Removes all listeners, or those of
the specified event. It's not a good idea to remove listeners that
were added elsewhere in the code, especially when it's on an
emitter that you didn't create (e.g. sockets or file streams). Returns
emitter, so calls can be chained.
setMaxListeners(n) : By default, EventEmitters will print a warning
if more than 10 listeners are added for a particular event. This is a
useful default state which helps finding memory leaks. Obviously not
all Emitters should be limited to 10. This function allows that to be
increased. Set to zero for unlimited.
listeners(event) : Returns an array of listeners for the specified
event.
emit(event, [arg1], [arg2], [...]) : Executes each of the listeners
in order with the supplied arguments. Returns true if the event had
listeners, false otherwise.
Class Methods
listenerCount(emitter, event) : Returns the number of listeners for a
given event.
Example: create a file named listenerCount.js saved on your
machine,
eventEmitter.emit('connection');
eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
Output:
Events
newListener
// listener #1
console.log('listner1 executed.');
// listener #2
console.log('listner2 executed.');
eventEmitter.addListener('connection', listner1);
eventEmitter.on('connection', listner2);
(eventEmitter,'connection');
eventEmitter.emit('connection');
// Remove the binding of listner1 function
eventEmitter.removeListener('connection', listner1);
eventEmitter.emit('connection');
eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log("Program Ended.");
listner1 executed.
listner2 executed.
listner2 executed.
Program Ended.
Assessment: Quiz
If an EventEmitter does not have at least one listener registered for the 'error' event,
and an 'error' event is emitted, the error is dismissed, a stack trace is printed, and
the Node.js process ____.
continues exits
Which method can be used to handle an event for just only one time?
Unlimited 10
By default EventEmitters will print a warning if more than ______ listeners are added
for a particular event:
10 20 30 100
When the EventEmitter object emits an event, all of the functions attached to that
specific event are called _______. Any values returned by the called listeners are
ignored and will be discarded.
synchronously asynchronously
All objects that emit events are instances of the EventEmitter class.
True False
File System
Synchronous vs Asynchronous
File System
Node implements File I/O using simple wrappers around standard POSIX
functions. The Node File System (fs) module can be imported using the
following syntax:
var fs = require("fs")
Example
Create a text file named input.txt with the following content:
Dummy Text For Testing !!!!
Let us create a .js file named main.js with the following code:
var fs = require("fs");
// Asynchronous read
return console.error(err);
});
// Synchronous read
console.log("Program Ended");
Program Ended
Let's take a look at a set of good examples on major File I/O methods:
Open a File
Syntax
The following is the method's syntax for opening a file in asynchronous
mode:
fs.open(path, flags[, mode], callback)
Parameters
Here is the description of the parameters used :
path − This is the string that has the file name and the path.
flags − Flags indicate the behavior of the file to be opened. All possible
values have been mentioned below.
mode − It sets the file mode (permission and sticky bits), but only if the
file was created. It defaults to 0666, readable and writeable.
callback − This is the callback function which gets two arguments (err,
fd).
Flags
r : Opens file for reading. An exception occurs if the file does not exist.
r+ : Opens file for reading and writing. An exception occurs if the file does
not exist.
rs : Opens file for reading in synchronous mode.
rs+ : Opens file for reading and writing, asking the OS to open it
synchronously. See notes for 'rs' about using this with caution.
w : Opens file for writing. The file is created (if it does not exist) or
truncated (if it exists).
wx : Like 'w' but fails if the path exists.
w+ : Opens file for reading and writing. The file is created (if it does not
exist) or truncated (if it exists).
wx+ : Like 'w+' but fails if path exists.
a : Opens file for appending. The file is created if it does not exist.
ax : Like 'a' but fails if the path exists.
a+ : Opens file for reading and appending. The file is created if it does not
exist.
ax+ : Like 'a+' but fails if the the path exists.
Example
Let us create a .js file named main.js that has the following code for
opening an input.txt file for reading and writing:
var fs = require("fs");
if (err) {
return console.error(err);
});
Parameters
Here is the description of the parameters used:
path − This is the string that has the file name and the path.
callback − This is the callback function which gets two arguments (err,
stats) where stats is an object of fs.Stats type which is printed below in the
example.
Apart from the important attributes which are printed below in the
example, there are several useful methods available in fs.Stats class
which can be used to check file type. These methods are given in the
following list:
Example
Let us create a js file named main.js with the following code
var fs = require("fs");
if (err) {
return console.error(err);
console.log(stats);
});
dev: 1792,
mode: 33188,
nlink: 1,
uid: 48,
gid: 48,
rdev: 0,
blksize: 4096,
ino: 4318127,
size: 97,
blocks: 8,
isDirectory ? false
Writing a File
Syntax
The following is one of the methods' syntax for writing into a file:
fs.writeFile(filename, data[, options], callback)
This method will over-write the file if the file already exists. If you want to
write into an existing file then you should use another method available.
Parameters
Here is the description of the parameters used :
path − This is the string having the file name including path.
data − This is the String or Buffer to be written into the file.
options − The third parameter is an object which will hold {encoding,
mode, flag}. By default. encoding is utf8, mode is octal value 0666. and
flag is 'w'
callback − This is the callback function which gets a single parameter err
that returns an error in case of any writing error.
Example
Let us create a js file named main.js having the following code :
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
return console.error(err);
});
});
Reading a File
Syntax
The following is one of the methods' syntax for reading from a file:
fs.read(fd, buffer, offset, length, position, callback)
This method will use a file descriptor to read the file. If you want to read
the file directly using the file name, then you should use another method
available.
Parameters
Here is the description of the parameters used:
if (err) {
return console.error(err);
if (err){
console.log(err);
console.log(buf.slice(0, bytes).toString());
});
});
67 bytes read
Closing a File
Syntax
The following is the syntax for closing an opened file:
fs.close(fd, callback)
Parameters
Here is the description of the parameters used:
Example
Let us create a js file named main.js having the following code
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
console.log(err);
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
fs.close(fd, function(err) {
if (err) {
console.log(err);
});
});
});
Truncate a File
Syntax
The following is the method's syntax for truncating an opened file:
fs.ftruncate(fd, len, callback)
Parameters
Here is the description of the parameters used:
Example
Let us create a .js file named main.js that has the following code:
var fs = require("fs");
if (err) {
return console.error(err);
if (err) {
console.log(err);
if (err) {
console.log(err);
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
fs.close(fd, function(err) {
if (err) {
console.log(err);
});
});
});
});
Dummy Text
File closed successfully.
Delete a File
Syntax
The following is the method's syntax for deleting a file:
fs.unlink(path, callback)
Parameters
Here is the description of the parameters used :
Example
Let us create a .js file named main.js having the following code
var fs = require("fs");
fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
});
Parameters
Here is the description of the parameters used:
Example
Let us create a .js file named main.js having the following :
var fs = require("fs");
fs.mkdir('/tmp/test',function(err) {
if (err) {
return console.error(err);
});
Read a Directory
Syntax
The following is the method's syntax for reading a directory:
fs.readdir(path, callback)
Parameters
Here is the description of the parameters used:
Example
Let us create a js file named main.js having the following code:
var fs = require("fs");
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
console.log( file );
});
});
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test
test.txt
Remove a Directory
Syntax
The following is the method's syntax for removing a directory:
fs.rmdir(path, callback)
Parameters
Here is the description of the parameters used:
Example
Let us create a .js file named main.js having the following code:
var fs = require("fs");
fs.rmdir("/tmp/test",function(err) {
if (err) {
return console.error(err);
fs.readdir("/tmp/",function(err, files) {
if (err) {
return console.error(err);
console.log( file );
});
});
});
ccmzx99o.out
ccyCSbkF.out
employee.ser
hsperfdata_apache
test.txt
Assessment: Quiz
'FS' is an acronym for
'Saved!' and then 'End of code' 'End of code' and then 'Saved!' 'End of
code' then 'Titatnic' and then 'Saved!'
What is the difference between writeFile and appendFile?
The fs.writeFile() method replaces the specified file and content if it exists while
fs.appendFile appends data to a file The first is synchronous and the second is
asynchronous
What is the result of the following code:
the content of the file as string value the content of the file as raw buffer
Which FS module method is used to open a file?
Global Objects
__filename
Node.js global objects are global in nature and they are available in all
modules. We do not need to include these objects in our application, but
instead, we can use them directly. These objects are modules, functions,
strings and objects themselves. We will explain more in the upcoming
slides.
The __filename represents the filename of the code being executed. This is
the resolved absolute path of the code file. For a main program, this is not
necessarily the same filename used in the command line. The value inside
a module is the path to that module's file.
Example
Create a .js file named main.js with the following code:
// Let's try to print the value of __filename
console.log( __filename );
Based on the location of your program, it will print the main file name as
follows:
/web/com/1427091028_21099/main.js
__dirname
The __dirname represents the name of the directory that the currently
executing script resides in.
Example
Create a .js file named main.js with the following code:
// Let's try to print the value of __dirname
console.log( __dirname );
Based on the location of your program, it will print current directory names
as follows:
/web/com/1427091028_21099
setTimeout(cb, ms)
The setTimeout(cb, ms) global function is used to run callback (cb)
after at least ms milliseconds. The actual delay depends on external
factors like OS timer granularity and system load. A timer cannot span
more than 24.8 days.
Example
Create a .js file named main.js with the following code:
function printHello() {
setTimeout(printHello, 2000);
Example
Create a .js file named main.js with the following code:
function printHello() {
clearTimeout(t);
Verify the output where you will not find anything printed.
setInterval(cb, ms)
The setInterval(cb, ms) global function is used to run a
callback cb repeatedly after at least a few ms milliseconds. The actual
delay depends on external factors like OS timer granularity and system
load. A timer cannot span more than 24.8 days.
This function returns an opaque value that represents the timer which can
be used to clear the timer using the function clearInterval(t).
Example
Create a .js file named main.js with the following code:
function printHello() {
}
// Now call above function after 2 seconds
setInterval(printHello, 2000);
The above program will execute printHello() after every 2 second. Due to
system limitation.
Assessment: Quiz
The __filename give us:
The name of the file being executed and its absolute path. The list of files in
the directory. The list of files in the directory.
The setTimeout(cb,ms) allows us to
Run the program after a period of time. Run the cb function after the time has
passed. Create a time interval in the callback parameters.
Which of the following is true about global objects in Node applications?
Global objects are global in nature and they are available in all modules.
Global objects are not required to be included in an application, rather they can be
used directly. None of the above.
Utility Modules
There are several utility modules available in the Node.js module library.
Among the most frequently used, we can mention the following, make
sure to check them out:
OS Module:
Provides basic operating-system related utility functions.
Path Module:
Provides utilities for handling and transforming file paths.
Net Module:
Provides both servers and clients as streams. Acts as a network
wrapper.
DNS Module:
Provides functions to do actual DNS lookup as well as to use
underlying operating system name resolution functionalities.
Domain Module:
Provides ways to handle multiple different I/O operations as a single
group.
Assessment: Quiz
The OS module provides operating system related utility methods and properties.
True False
The net module provides an asynchronous network API for creating stream-based
TCP or IPC servers.
True False
What is a module?
Web Module
What is a Web Server?
A Web Server is a software application which handles HTTP requests sent
by the HTTP client, like web browsers, and returns web pages in response
to the clients. Web servers usually deliver HTML documents along with
images, style sheets, and scripts.
Most of the web servers support server-side scripts. They use scripting
languages and redirect the task to an application server which retrieves
data from a database and performs complex logic. Finally a result is sent
to the HTTP client through the web server.
File: server.js
var http = require('http');
var fs = require('fs');
// Create a server
if (err) {
console.log(err);
} else {
//Page found
response.write(data.toString());
response.end();
});
}).listen(8081);
File: index.html
<html>
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
File: client.js
var http = require('http');
var options = {
host: 'localhost',
port: '8081',
path: '/index.html'
};
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
console.log(body);
});
req.end();
Now run the client.js from a different command terminal other than
server.js to see the result:
$ node client.js
<head>
<title>Sample Page</title>
</head>
<body>
Hello World!
</body>
</html>
Assessment: Quiz
Select the Node.js module types from the following options:
HTTP URL FS
To use the HTTP module, we have to use:
Conclusion
Node.js RECAP
Congratulation! By now, we can say we're pretty good with Node.js. We're
able to create and manipulate a web server using Node.js. The main
important thing is that we understand how Node.js treats the async event
and function and that is pretty impressive.
Express (Routing)
Express (Routing) Introduction
What is Express.js ?
After the big rise of Node.js, there are plenty of frameworks and library
that have been created. The most used one for backend rendering is
Express. That will be the topic of this Super Skill. So during this chapter we
are going to explore:
What is Express?
How to setup an Express environment?
What is routing via Express?
What are middlewares and what is their use?
How to work with a template engine?
What is Express.js ?
The Express website describes Express as a "minimal and flexible Node.js
web application framework that provides a robust set of features for web
and mobile applications." What does that really mean, exactly?
Express provides basic tools that facilitate the creation of Node.js
applications without obscuring Node.js features that you know and love.
It provides a set of methods for processing HTTP requests and provides a
middleware system that extends its functionality.
It also makes it easier to manage the path (URL) of your application and
not to mention that it uses templates.
If you have wrote any serious apps only using the core Node.js modules,
you must have likely found yourself reinventing the wheel by repeatedly
writing the same code for the same tasks such as:
Assessment: Quiz
What are the core features of Express framework?
Environment
Installation
Assuming you’ve already installed Node.js, you should create a directory
to hold your application and make that your working directory.
$ mkdir myapp
$ cd myapp
This command prompts you a number of things, such as the name and
version of your application. For now, you can simply hit RETURN to accept
the defaults for most of them, with the following exception:
entry point: (index.js)
Enter app.js, or whatever you want the name of the main file to be. If you
want it to be index.js, hit RETURN to accept the suggested default file
name.
Finally, we can install the module utilizing NPM
$ npm install express --save
$ express
For example, the following creates an Express app named myapp. The app
will be created in a folder named myapp in the current working directory
and the view engine will be set to Pug:
$ express --view=pug myapp
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.pug
├── index.pug
└── layout.pug
7 directories, 9 files
$ npm install
Options:
Assessment: Quiz
To install Node.js express module, we use
$ npm install express --save $ npm install express $ node install express
$ npm install
To generate an express application skeleton without view engine, we use
The application is a web server that will run locally on port 4000:
const port = 4000;
port);
});
});
app.listen(port, function(){
port);
});
To run the script, we execute node index.js from the project folder:
$ node index
res.status(200);
res.set('Content-type', 'text/html');
res.send('<html><body>' +
);
});
app.get('/name/:user_name', function(req,res) {
res.status(200);
res.set('Content-type', 'text/html');
res.send('<html><body>' +
'</body></html>'
);
});
res.end('Hello World');
});
app.listen(port, function(){
port);
});
After shutting down the previous server and launching the index.js script,
you’ll be able to see the dynamic response, e.g., by
entering http://localhost:4000/name/Gomycode in your browser yields:
Assessment: Quiz
How can we use express?
The following code is an example of routes that are defined for the GET
and the POST methods to the root of the app.
// GET method route
})
})
})
});
string
string patterns
regular expressions.
If you need to use the dollar character ($) in a path string, enclose it within
([ and ]). For example, the path string for requests at “/data/$book”, would
be “/data/([$])book”.
Here are some examples of route paths based on strings.
res.send('about');
})
res.send('random.text');
})
res.send('ab?cd');
})
This route path will match abcd, abbcd, abbbcd, and so on.
app.get('/ab+cd', function (req, res) {
res.send('ab+cd');
})
This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so
on.
app.get('/ab*cd', function (req, res) {
res.send('ab*cd');
})
})
res.send('/a/');
})
This route path will match butterfly and dragonfly, but not butterflyman,
dragonflyman, and so on.
app.get(/.*fly$/, function (req, res) {
res.send('/.*fly$/');
})
Route Parameters
The route parameters are used to capture the values that are assigned to
a particular position in the URL. They are called the URL segments.
The values obtained are made available in a req.params object, using the
name of the route parameter specified in the path as the values' keys.
Route path: /users/:userId/books/:bookId
res.send(req.params)
})
To have more control over the exact string that can be matched by a route
parameter, you can append a regular expression in parentheses (()):
Route path: /user/:userId(\d+)
//do authorization
//return next(error);
return next();
req.story = story;
return next();
}), function(req,res) {
res.send(res.story);
});
...
return next();
...
return next();
}
const renderUsers = function (req, res) {
res.end();
app.get('/admin', admin);
app.route()
You can create chainable route handlers for a route path by using
app.route(). Because the path is specified at a single location, creating
modular routes is helpful, as well as reducing redundancies and typos.
Here is an example of chained route handlers that are defined by using
app.route().
app.route('/book')
})
res.send('Add a book');
})
})
app.route()
The express.Router middleware allows us to group the route handlers for a
particular part of a site together and access them using a common route-
prefix.
The code below provides a concrete example of how we can create a route
module and then use it in an Express application.
First, we create routes for a post in a module named post.js. Then, the
code imports the Express application object, uses it to get a Router object,
and adds a couple of routes to it using the get() method. Lastly, the
module exports the Router object.
router.route('/post/:slug')
})
//render post
})
//update post
})
})
//remove post
});
module.exports = router
To use the router module in our main app file we first require() the route
module (post.js). We then call use() on the Express application to add the
router to the middleware handling path while specifying the URL path of
'/blog'.
const post = require(‘./post’);
app.use(‘/blog, post);
Assessment: Quiz
Route paths, in combination with a request method, define the endpoints at which
requests can be made. Which of the following are a valid form of route path?
req - the request object res - the response object Next All of the above
How many number of callback functions can be attached to handle a request?
True False
Is the following code valid?
True False
Middleware
Middleware Introduction
Middleware functions are functions that have access to the request
object (req), the response object (res), and the next function in the
application’s request-response cycle.
The next function is a function in the Express router that, when invoked,
executes the middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
next();
}
To load the middleware function, call app.use(), specifying which
middleware function. For example, the following code loads the myLogger
middleware function before the route to the root path (/).
const express = require('express');
next();
app.use(myLogger);
res.send('Hello World!')
})
app.listen(3000);
The above middleware is called for every request on the server. So after
every request, we will get the following message in the console:
A new request received at 1584954785016
next();
});
res.send('Things');
});
app.listen(3000);
Now, whenever you request any subroute of '/things', that will be the
instance where it will log the time.
Error-handling middleware
Express JS comes with default error handling parameters. We can define
error-handling middleware functions in the same way as other middleware
functions, except error-handling functions have four arguments instead of
three:
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
});
If you pass anything to the next() function (except the string 'route'),
Express regards the current request as being an error and will skip any
remaining non-error handling routing and middleware functions.
app.use(bodyParser.json())
To view all available options for the body-parser middleware, visit its
GitHub page.
app.use(cookieParser())
Middleware Order is Important
When a request is received by Express, each middleware that matches the
request is run in the order it is initialized in until there is a concluding
action (like a response being sent).
So if an error occurs, all middlewares that are assigned to handle errors will be
called in order until one of them does not call the next() function call.
Template Engines
Template engines Introduction
A template engine facilitates the use of static template files in your
applications. At runtime, it replaces variables in a template file with actual
values, and transforms the template into an HTML file sent to the client. So
this approach is favoured because it allows us to design HTML pages
easily.
Some popular template engines that work with Express are Pug, Mustache,
and EJS. The Express application generator uses Pug (formerly known as
jade) as its default one, but it also supports several others.
See Template Engines (Express wiki) for a list of template engines you can
use with Express. See also Comparing JavaScript Templating Engines: Pug,
Mustache, Dust and More.
Install Pug
Execute the following command to install Pug template engine:
npm install pug --save
app.set('views','./views');
Now create a new directory called "views". Inside it, create a file called
first_view.pug, and enter the following data in.
doctype html
html
head
body
});
<html>
<head>
<title>Hello Pug</title>
</head>
<body>
</body>
</html>
Simple Tags
Tags are nested according to their indentation. Like in the example
before, <title> was indented within the <head> tag, so it was inside it.
But, the <body> tag was on the same indentation and that means it is a
sibling of the <head> tag.
We don’t need to close tags. As soon as Pug encounters the next tag on
the same or outer indentation level, it closes the tag automatically.
We have 3 methods for putting text inside a tag:
Space separated
h1 Welcome to Pug
Piped text
div
| To insert multiple lines of text,
Block of text
div.
You can use "." at the end of a tag to denote a block of text.
To put tags inside this block, simply enter tag in a new line and
indent it accordingly.
Comments
Pug uses the same syntax as JavaScript(//) for creating comments. These
comments are converted into HTML comments(<!--comment-->). For
example,
//This is a Pug comment
Attributes
To define attributes, we use a list of attributes that are separated by
commas and put them inside parenthesis. Class and ID attributes have
special representations. The following line of code covers defining
attributes, classes and HTML tag ID.
div.container.column.main#division(width = "100", height = "100")
res.render('dynamic', {
name: “Gomycode",
url:"http://www.tutorialspoint.com"
});
});
app.listen(3000);
And create a new view file in views directory, called dynamic.pug, with the
following code
html
head
title=name
body
h1=name
head
title = name
body
This method of using values is called interpolation. The above code will
display the following output.
head
if(user)
h1 Hi, #{user.name}
else
When we render this using our routes, we can pass an object as in the
following program
res.render('/dynamic',{
});
You will receive a message − Hi, Ayush. But if we don’t pass any object or
pass one with no user key, then we will get a signup link.
HEADER.PUG
div.header.
CONTENT.PUG
html
head
body
include ./header.pug
include ./footer.pug
FOOTER.PUG
div.footer.
res.render('content');
});
app.listen(3000);
Assessment: Quiz
What are the names of the template engines imposed by Express.js?
True False
Can we create our own template engine?
True False
Conclusion
Express Routing RECAP
Kudos to you for making it this far!
After diving deep into this Super Skill, we have covered the basics of
Express.js. It is a super powerful framework for backend rendering, but
that is not all.
For the time being, we have only seen the server part in backend
development. There are still more tools to learn. Let's jump into the next
Super Skill.