Unit 1
Unit 1
Node.js Tutorial
Node.js tutorial provides basic and advanced concepts of Node.js. Our Node.js tutorial is
designed for beginners and professionals both.
Our Node.js tutorial includes all topics of Node.js such as Node.js installation on windows
and Linux, REPL, package manager, callbacks, event loop, os, path, query string,
cryptography, debugger, URL, DNS, Net, UDP, process, child processes, buffers, streams,
file systems, global objects, web modules etc. There are also given Node.js interview
questions to help you better understand the Node.js technology.
What is Node.js
Node.js is a cross-platform runtime environment and library for running JavaScript
applications outside the browser. It is used for creating server-side and networking web
applications. It is open source and free to use. It can be downloaded from this
link https://nodejs.org/en/
Many of the basic modules of Node.js are written in JavaScript. Node.js is mostly used to
run real-time server applications.
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model that
1
Shri V J Modha College of IT
Unit - 1
makes it lightweight and efficient, perfect for data-intensive real-time applications that
run across distributed devices.?
Node.js also provides a rich library of various JavaScript modules to simplify the
development of web applications.
2
Shri V J Modha College of IT
Unit - 1
Features of Node.js
Following is a list of some important features of Node.js that makes it the first choice of
software architects.
3
Shri V J Modha College of IT
Unit - 1
Install Node.js on Windows
To install and setup an environment for Node.js, you need the following two softwares
available on your computer:
1. Text Editor.
2. Node.js Binary installable
Text Editor:
The text editor is used to type your program. For example: Notepad is used in Windows,
vim or vi can be used on Windows as well as Linux or UNIX. The name and version of the
text editor can be different from operating system to operating system.
The files created with text editor are called source files and contain program source code.
The source files for Node.js programs are typically named with the extension ".js".
The source code written in source file is simply JavaScript. It is interpreted and executed
by the Node.js interpreter.
You can download the latest version of Node.js installable archive file
from https://nodejs.org/en/
4
Shri V J Modha College of IT
Unit - 1
Here, you deploy the installation of node-v4.4.2 LTS recommended for most users.
5
Shri V J Modha College of IT
Unit - 1
ADVERTISEMENT
6
Shri V J Modha College of IT
Unit - 1
7
Shri V J Modha College of IT
Unit - 1
Ready to install:
8
Shri V J Modha College of IT
Unit - 1
9
Shri V J Modha College of IT
Unit - 1
Node.js First Example
There can be console-based and web-based node.js applications.
1. console.log('Hello JavaTpoint');
1. node console_example1.js
10
Shri V J Modha College of IT
Unit - 1
Follow these steps:
1. Import required module: The first step is to use “require” directive to load http
module and store returned HTTP instance into http variable. For example:
1. var http = require("http");
2. Create server: In the second step, you have to use created http instance and call
http.createServer() method to create server instance and then bind it at port 8081
using listen method associated with server instance. Pass it a function with request
and response parameters and write the sample implementation to return "Hello
World". For example:
File: main.js
11
Shri V J Modha College of IT
Unit - 1
11. console.log('Server running at http://127.0.0.1:8081/');
12
Shri V J Modha College of IT
Unit - 1
So type cd desktop on the command prompt. After that execute the main.js to start the
server as follows:
1. node main.js
13
Shri V J Modha College of IT
Unit - 1
Make a request to Node.js server:
Open http://127.0.0.1:8081/ in any browser. You will see the following result.
Now, if you make any changes in the "main.js" file, you need to again run the "node
main.js" command.
14
Shri V J Modha College of IT
Unit - 1
15
Shri V J Modha College of IT
Unit - 1
Difference between Nodejs, AJAX, and jQuery:
16
Shri V J Modha College of IT
Unit - 1
Difference between Primitive vs Non-Primitive
Primitive Non-Primitive
Examples are numbers and strings. Examples are Array and Linked List.
17
Shri V J Modha College of IT
Unit - 1
Primitive data types:
The predefined data types provided by JavaScript language are known as primitive
data types. Primitive data types are also known as in-built data types.
Below is a list of Primitive Data Types with proper descriptions and examples:
Number
Number data type in JavaScript can be used to hold decimal values as well as values
without decimals.
Example: Below is an example.
JavaScript
let x = 250;
let y = 40.5;
console.log("Value of x=" + x);
console.log("Value of y=" + y);
Output
Value of x=250
Value of y=40.5
String
The string data type in JavaScript represents a sequence of characters that are
surrounded by single or double quotes.
Example: Below is an example.
JavaScript
Output
18
Shri V J Modha College of IT
Unit - 1
Undefined
This means that a variable has been declared but has not been assigned a value, or it
has been explicitly set to the value `undefined`.
Example: Below is an example.
JavaScript
let x;
console.log(x); // Outputs: undefined
Output:
undefined output
Boolean
The boolean data type can accept only two values i.e. true and false.
Example: Below is an example.
JavaScript
let x;
console.log(x); // Outputs: undefined
Output:
boolean output
19
Shri V J Modha College of IT
Unit - 1
Null
This data type can hold only one possible value that is null.
Example: Below is an example.
JavaScript
let x = null;
console.log("Value of x=" + x);
Output
Value of x=null
BigInt
BigInt data type can represent numbers greater than 253-1 which helps to perform
operations on large numbers. The number is specified by writing ‘n’ at the end of the
value
Example: Below is an example.
JavaScript
Output
123422222222222222222222222222222222222n
Symbol
Symbol data type is used to create objects which will always be unique. these objects
can be created using Symbol constructor.
Example: Below is an example.
JavaScript
Output
symbol
Symbol(Hello)
20
Shri V J Modha College of IT
Unit - 1
Non-primitive data types:
The data types that are derived from primitive data types of the JavaScript language
are known as non-primitive data types. It is also known as derived data types or
reference data types.
Below is a list of Non-primitive data types.
Object
Array
21
Shri V J Modha College of IT
Unit - 1
Object
An object in Javascript is an entity having properties and methods. Everything is an
object in javascript.
How to create an object in javascript:
• Using Constructor Function to define an object:
// Create an empty generic object
let obj = new Object();
Output
Luiza Shaikh
22
Shri V J Modha College of IT
Unit - 1
Array
With the help of an array, we can store more than one element under a single name.
Ways to declare a single-dimensional array:
// Call it with no arguments
let a = new Array();
Output
value of a=
value of b,,,,,,,,,
value of d=1,2,3,Hello
Note: JavaScript does not support two-dimensional arrays. but we can do this by
creating an array of an array.
23
Shri V J Modha College of IT
Unit - 1
What is Loosely Typed Language?
A programming language that does not demand the definition of a variable is known as
a loosely typed language. For instance, Perl is a flexibly typed language that allows
you to declare variables without having to specify the type of the variable. The $test
variable, which in the example below can be used as either an integer or a string, is
declared in the first line.
Strong and Loose/Weakly typed programming languages can be used to categorize all
programming languages. Each of these classes has advantages and disadvantages in the
realm of programming and defines how rigorous the programming language is.
A programming language for computers that does not data type of a variable is referred
to as being loosely typed language. In comparison to strongly typed languages, this
language makes it simple to define variables with various data types. A data type
essentially tells the compiler what kind of value and actions this specific variable may
store.
Strong bounds on the variable data type are not available in a loosely typed language.
This kind of language's compiler executes the operation specified on it regardless of the
data type it contains when doing compilation. The compiler ignores small errors
depending on data types.
Let's use an example to make our point clearer. Suppose you construct a variable in a
loosely typed language, initialize it with a number, and then declare that you want to store
a string in this variable later. Because it does not throw any errors during compilation,
loosely typed languages provide you the freedom to swap out values.
24
Shri V J Modha College of IT
Unit - 1
What features define a language that is loosely
typed?
1. In comparison to strongly typed languages, these languages provide less rigid typing
restrictions.
2. Many data types are implicitly transformed over the course of a program's execution.
3. No of what type of data they are currently in, variables can be simply converted into
another data type.
4. There is no need to identify the data type of a variable when declaring it.
5. These languages do not have any compile-time or run-time checks for breaches of data
type constraints.
2. Choice in programming
The freedom to build and manipulate their own programming rules is provided by loosely
typed languages like PHP for developers. On the other hand, the developers of a program
written in a strongly typed language must adhere strictly to the predefined rules for the
program to execute.
3. Reusability of Code
A variable can be used again in this language once it has been declared anytime it is
necessary. According to developers, a specific variable can be used more than once to
store various data kinds. In the case of complex programs, it is very useful for making the
code appear organized and shorter.
25
Shri V J Modha College of IT
Unit - 1
4. Faster and with less memory usage
These languages are simple and operate more quickly than strongly typed languages.
These languages render complex applications at a significantly faster rate. They also
require less memory. Applications with complexity are rendered because these languages
enable developers to reuse variables.
26
Shri V J Modha College of IT
Unit - 1
What distinguishes a language that is loosely typed from
one that is strongly typed?
It is necessary to specify the data type of a It's not necessary to specify the data type of a
variable. variable.
This prevents simple data type conversion. This makes data type conversion simple.
Eg. Java, c++, c, c#, python, etc Eg. Javascript, typescript, php, etc
27
Shri V J Modha College of IT
Unit - 1
Node.js Literal
In Node.js (and JavaScript in general), literals are fixed values that you write directly into
the code. There are several types of literals in JavaScript, including:
1. String Literals: Used to represent textual data. You can use single quotes ('),
double quotes ("), or backticks (`) for template literals.
javascript
Copy code
const isTrue = true;
const isFalse = false;
const obj = {
name: 'Alice',
age: 30
};
28
Shri V J Modha College of IT
Unit - 1
6. RegExp Literals: Used to create regular expressions.
let notAssigned;
These literals are the basic building blocks for creating and manipulating data in Node.js
applications. They allow you to directly specify values in your code without needing to
construct them programmatically.
29
Shri V J Modha College of IT
Unit - 1
Node.js Functions
In Node.js (and JavaScript in general), functions are fundamental building blocks that
encapsulate reusable code. Functions can be defined in several ways, and they serve
various purposes, such as organizing code, performing computations, and handling
events. Here's an overview of the different aspects of functions in Node.js:
1. Function Declaration
A function declaration defines a named function. This type of function can be called
before it is defined in the code due to hoisting.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
2. Function Expression
3. Arrow Functions
Arrow functions provide a shorter syntax and lexically bind the this value, making them
useful in certain contexts like callbacks and methods.
4. Anonymous Functions
Anonymous functions are functions without a name. They are often used as arguments
to other functions or as immediately invoked function expressions (IIFEs).
30
Shri V J Modha College of IT
Unit - 1
setTimeout(function() {
console.log('This runs after 1 second');
}, 1000);
An IIFE is a function that runs as soon as it is defined. It is used to create a local scope
and avoid polluting the global namespace.
(function() {
console.log('This runs immediately');
})();
6. Callback Functions
Callback functions are passed as arguments to other functions and are invoked after
some operation is completed. They are widely used in asynchronous programming.
const fs = require('fs');
7. Higher-Order Functions
31
Shri V J Modha College of IT
Unit - 1
const doubled = map([1, 2, 3], num => num * 2);
console.log(doubled); // [2, 4, 6]
8. Async/Await Functions
Async functions are a modern way to handle asynchronous operations. They return a
promise, and the await keyword can be used to wait for the promise to resolve.
const fs = require('fs').promises;
readFile();
9. Method Functions
Methods are functions defined inside an object or a class. They can use the this keyword
to refer to the object they belong to.
const obj = {
name: 'Alice',
greet() {
console.log(`Hello, ${this.name}`);
}
};
Functions in Node.js are versatile and can be used in various ways to create efficient,
modular, and maintainable code. Understanding how to define and use functions is
crucial for effective Node.js development.
32
Shri V J Modha College of IT
Unit - 1
Node.js Buffers
Node.js provides Buffer class to store raw data similar to an array of integers but
corresponds to a raw memory allocation outside the V8 heap. Buffer class is used because
pure JavaScript is not nice to binary data. So, when dealing with TCP streams or the file
system, it's necessary to handle octet streams.
Buffer class is a global class. It can be accessed in application without importing buffer
module.
2. Create a buffer from array: Following is the syntax to create a Buffer from a given
array:
3. Create a buffer from string: Following is the syntax to create a Buffer from a given
string and optionally encoding type:
Syntax:
Parameter explanation:
33
Shri V J Modha College of IT
Unit - 1
offset: It specifies the index of the buffer to start writing at. Its default value is 0.
This method is used to return number of octets written. In the case of space shortage for
buffer to fit the entire string, it will write a part of the string.
File: main.js
Open the Node.js command prompt and execute the following code:
1. node main.js
Output:
34
Shri V J Modha College of IT
Unit - 1
Node.js Reading from buffers
Following is the method to read data from a Node buffer.
Syntax:
Parameter explanation:
This method decodes and returns a string from buffer data encoded using the specified
character set encoding.
File: main.js
35
Shri V J Modha College of IT
Unit - 1
Open Node.js command prompt and execute the following code:
1. node main.js
Output:
36
Shri V J Modha College of IT
Unit - 1
Node.js Process
Node.js provides the facility to get process information such as process id, architecture,
platform, version, release, uptime, upu usage etc. It can also be used to kill process, set
uid, set groups, unmask etc.
Property Description
platform returns platform of the process: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
File: process_example1.js
37
Shri V J Modha College of IT
Unit - 1
3. console.log(`Process Platform: ${process.platform}`);
4. console.log(`Process Version: ${process.version}`);
1. node process_example1.js
Let's see another process example to print command line arguments. Here node is
considered as the first argument, filename is considered as the second argument and
actual command line arguments are considered as third, fourth, fifth and so on.
File: process_example2.js
1. node process_example2.js
38
Shri V J Modha College of IT
Unit - 1
Node.js Process Functions
A list of commonly used Node.js process functions are given below.
Function Description
File: process_example3.js
1. node process_example3.js
39
Shri V J Modha College of IT
Unit - 1
Access global scope
A scope can be defined as the region of the execution, a region where the expressions
and values can be referenced.
There are two scopes in JavaScript that are global and local:
Global Scope: In the global scope, the variable can be accessed from any part of
the JavaScript code.
Local Scope: In the local scope, the variable can be accessed within a function where it is
declared.
In the function's body, the precedence of the local variable is more than the global
variable with the same name. If the name of the function's local variable is same as the
name of the global variable, then the local variable hides the global variable.
40
Shri V J Modha College of IT
Unit - 1
Example1
In this example, we are declaring two variables one variable has a global scope, and the
second variable has local scope. Both of the variables are declared with the same name.
In the output, we can see that the variable with locally scoped overrides the value of the
global variable.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. </head>
5. <body>
6. <script>
7. var $var12 = 200;
8.
9. function example() {
10. var $var12 = 300;
11. document.write("Inside example() function = " + $var12);
12. }
13. document.write("Outside example() function = " + $var12);
14. document.write("<br>");
15. example();
16. </script>
17.
18. </body>
19. </html>
Output
41
Shri V J Modha College of IT
Unit - 1
When we declare a variable inside a function without using the var keyword, it acts as a
global variable. Let's see an illustration of the same.
Example2
In this example, we are declaring a variable inside the function without using any variable
declaration keyword. Then we are accessing the corresponding variable outside the
function.
In the output, we can see that there is no error is generating related to the undefined
variable. The code is successfully executed without generating any error.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. </head>
5. <body>
6. <script>
7. function example() {
8. $var12 = 300;
9. document.write("Inside example() function = " + $var12);
10. }
11. example();
12. document.write("<br>");
13. document.write("Outside example() function = " + $var12);
14. </script>
15. </body>
16. </html>
Output
42
Shri V J Modha College of IT
Unit - 1
In the above code, if we use the variable without calling the function, then the variable is
undefined, and there is no output will be generated. In this case, the error will generate
related to the undefined variable.
43
Shri V J Modha College of IT