0% found this document useful (0 votes)
6 views43 pages

Unit 1

Uploaded by

jayvaghela1542
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views43 pages

Unit 1

Uploaded by

jayvaghela1542
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

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.

Node.js is a cross-platform environment and library for running JavaScript applications


which is used to create networking and server-side applications.

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.

The definition given by its official documentation is as follows:

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.

1. Node.js = Runtime Environment + JavaScript Library

Different parts of Node.js

The following diagram specifies some important parts of Node.js:

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.

1. Extremely fast: Node.js is built on Google Chrome's V8 JavaScript Engine, so its


library is very fast in code execution.
2. I/O is Asynchronous and Event Driven: All APIs of Node.js library are
asynchronous i.e. non-blocking. So a Node.js based server never waits for an API
to return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the
previous API call. It is also a reason that it is very fast.
3. Single threaded: Node.js follows a single threaded model with event looping.
4. Highly Scalable: Node.js is highly scalable because event mechanism helps the
server to respond in a non-blocking way.
5. No buffering: Node.js cuts down the overall processing time while uploading
audio and video files. Node.js applications never buffer any data. These
applications simply output the data in chunks.
6. Open source: Node.js has an open source community which has produced many
excellent modules to add additional capabilities to Node.js applications.
7. License: Node.js is released under the MIT license.

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 Node.js Runtime:

The source code written in source file is simply JavaScript. It is interpreted and executed
by the Node.js interpreter.

How to download Node.js:

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

Accept the terms of license agreement.

ADVERTISEMENT

6
Shri V J Modha College of IT
Unit - 1

Choose the location where you want to install.

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.

Node.js console-based Example


File: console_example1.js

1. console.log('Hello JavaTpoint');

Open Node.js command prompt and run the following code:

1. node console_example1.js

Here, console.log() function displays message on console.

Node.js web-based Example


A node.js web application contains the following three parts:

1. Import required modules: The "require" directive is used to load a Node.js


module.
2. Create server: You have to establish a server which will listen to client's request
similar to Apache HTTP Server.
3. Read request and return response: Server created in the second step will read
HTTP request made by client which can be a browser or console and return the
response.

How to create node.js web applications

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:

1. http.createServer(function (request, response) {


2. // Send the HTTP header
3. // HTTP Status: 200 : OK
4. // Content Type: text/plain
5. response.writeHead(200, {'Content-Type': 'text/plain'});
6. // Send the response body as "Hello World"
7. response.end('Hello World\n');
8. }).listen(8081);
9. // Console will print the message
10. console.log('Server running at http://127.0.0.1:8081/');

3. Combine step1 and step2 together in a file named "main.js".

File: main.js

1. var http = require("http");


2. http.createServer(function (request, response) {
3. // Send the HTTP header
4. // HTTP Status: 200 : OK
5. // Content Type: text/plain
6. response.writeHead(200, {'Content-Type': 'text/plain'});
7. // Send the response body as "Hello World"
8. response.end('Hello World\n');
9. }).listen(8081);
10. // Console will print the message

11
Shri V J Modha College of IT
Unit - 1
11. console.log('Server running at http://127.0.0.1:8081/');

How to start your server:

Go to start menu and click on the Node.js command prompt.

Now command prompt is open:

12
Shri V J Modha College of IT
Unit - 1

Set path: Here we have save "main.js" file on the desktop.

So type cd desktop on the command prompt. After that execute the main.js to start the
server as follows:

1. node main.js

Now server is started.

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

Non-Primitive data types are created by


Primitive Data types are predefined.
the programmer

Primitive Data types will have certain


Non-Primitive data types can be NULL.
values.

Size depends on the type of data


Size is not fixed
structure.

Examples are numbers and strings. Examples are Array and Linked List.

It can start with a lowercase. It can start with uppercase.

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

let str = 'Hello All';


let str1 = "Welcome to my new house";
console.log("Value of str=" + str);
console.log("Value of str1=" + str1);

Output

Value of str=Hello All


Value of str1=Welcome to my new house

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

let bigNum = 123422222222222222222222222222222222222n


console.log(bigNum)

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

let sym = Symbol("Hello")


console.log(typeof(sym));
console.log(sym);

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.

Non-primitive Data Types

Object

Array

Below is a list of Non-primitive Data Types with proper descriptions and


examples:

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();

// Create a user defined object


let mycar = new Car();
• Using Literal notations to define an object:
// An empty object
let square = {};

// Here a and b are keys and


// 20 and 30 are values
let circle = {a: 20, b: 30};
Example: Below is an example.
JavaScript

// Creating object with the name person


let person = {
firstName: "Luiza",
lastName: "Shaikh",
};

// Print the value of object on console


console.log(person.firstName
+ " " + person.lastName);

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();

// Call it with single numeric argument


let b = new Array(10);

// Explicitly specify two or


// more array elements
let d = new Array(1, 2, 3, "Hello");
Example: Below is an example.
JavaScript

let a = new Array();


let b = new Array(10);
let d = new Array(1, 2, 3, "Hello");
console.log("value of a=" + a);
console.log("value of b" + b);
console.log("value of d=" + d);

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.

The C programming language is an example of a strongly typed language, which is the


opposite of a weakly typed language.

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.

1. var v1= 23;


2. console.log(v1);
3. /*and here, the data type of variable named v1 is changed*/
4. v1 ="changed";
5. console.log(v1);

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.

What are the benefits of loosely typed language?


1. Allows for flexibility
Compared to strongly typed languages, these languages are far more flexible. These
languages are chosen over strongly typed languages to create dynamic applications
because of their flexibility. Working on dynamic applications can be challenging for
developers since these applications require users to make decisions based on unknown
facts. The reason being that they don't firmly associate a variable with a specific data type,
loosely typed languages make dealing with this situation fairly simple.

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.

5. Simple and economical


These languages are easy to learn and can function on any platform. Developers are drawn
to it because of its simplicity. These languages, like PHP, are free to use and
straightforward, making them cost-efficient as well.

What are the drawbacks of loosely typed language?


1. Bring About Unexpected Results
These languages frequently produce surprising results. If a string is provided to an
operation that was designed to operate on an integer data type, for example, the outcome
will be unpredictable and random. Developers must therefore exercise extra caution when
working with these kinds of languages.

2. difficult to debug code


It can be quite difficult to debug code in a loosely typed language as compared to strongly
typed languages. It might be quite challenging to identify the value that is stored in the
variable that produced the unexpected result because variables are allocated several times
inside the same application. However, specified rules and a high level of strictness are
provided by strongly typed languages, which make it simpler to reduce errors.

What are some examples of loosely typed language?


o Perl
o PHP
o JavaScript
o VB

26
Shri V J Modha College of IT
Unit - 1
What distinguishes a language that is loosely typed from
one that is strongly typed?

Strongly typed language Loosely typed language

It is necessary to specify the data type of a It's not necessary to specify the data type of a
variable. variable.

Programming flexibility is not permitted. It gives programming flexibility.

takes up more memory Takes up less memory

This prevents simple data type conversion. This makes data type conversion simple.

It has no flexibility. It has flexibility.

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.

const singleQuoteStr = 'Hello, world!';


const doubleQuoteStr = "Hello, world!";
const templateLiteralStr = `Hello, world!`;

2. Numeric Literals: Used to represent numbers. They can be integers or floating-


point numbers.

const integer = 42;


const float = 3.14;
const hexadecimal = 0x2A; // 42 in hexadecimal
const binary = 0b101010; // 42 in binary
const octal = 0o52; // 42 in octal

3. Boolean Literals: Represent true and false values.

javascript
Copy code
const isTrue = true;
const isFalse = false;

4. Object Literals: Used to create objects.

const obj = {
name: 'Alice',
age: 30
};

5. Array Literals: Used to create arrays.

const arr = [1, 2, 3, 4, 5];

28
Shri V J Modha College of IT
Unit - 1
6. RegExp Literals: Used to create regular expressions.

const regex = /ab+c/;

7. Template Literals: Enhanced string literals that support embedded expressions.

const name = 'Bob';


const greeting = `Hello, ${name}!`;

8. Null Literals: Represent the null value.

const nothing = null;

9. Undefined Literals: Represent an undefined value.

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

A function expression defines a function as part of a larger expression, usually by


assigning it to a variable. This type of function is not hoisted.

const add = function(a, b) {


return a + b;
};
console.log(add(2, 3)); // 5

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.

const add = (a, b) => a + b;


console.log(add(2, 3)); // 5

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);

5. Immediately Invoked Function Expressions (IIFE)

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');

fs.readFile('example.txt', 'utf8', (err, data) => {


if (err) {
console.error(err);
return;
}
console.log(data);
});

7. Higher-Order Functions

Higher-order functions take other functions as arguments or return them as output.


They are useful for functional programming.

function map(arr, fn) {


const result = [];
for (let i = 0; i < arr.length; i++) {
result.push(fn(arr[i]));
}
return result;
}

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;

async function readFile() {


try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}

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}`);
}
};

obj.greet(); // Hello, Alice

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.

Node.js Creating Buffers


There are many ways to construct a Node buffer. Following are the three mostly used
methods:

1. Create an uninitiated buffer: Following is the syntax of creating an uninitiated


buffer of 10 octets:
1. var buf = new Buffer(10);

2. Create a buffer from array: Following is the syntax to create a Buffer from a given
array:

1. var buf = new Buffer([10, 20, 30, 40, 50]);

3. Create a buffer from string: Following is the syntax to create a Buffer from a given
string and optionally encoding type:

1. var buf = new Buffer("Simply Easy Learning", "utf-8");

Node.js Writing to buffers


Following is the method to write into a Node buffer:

Syntax:

1. buf.write(string[, offset][, length][, encoding])

Parameter explanation:

string: It specifies the string data to be written to buffer.

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.

length: It specifies the number of bytes to write. Defaults to buffer.length

encoding: Encoding to use. 'utf8' is the default encoding.

Return values from writing buffers:

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.

Let's take an example:

Create a JavaScript file named "main.js" having the following code:

File: main.js

1. buf = new Buffer(256);


2. len = buf.write("Simply Easy Learning");
3. console.log("Octets written : "+ len);

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:

1. buf.toString([encoding][, start][, end])

Parameter explanation:

encoding: It specifies encoding to use. 'utf8' is the default encoding

start: It specifies beginning index to start reading, defaults to 0.

end: It specifies end index to end reading, defaults is complete buffer.

Return values reading from buffers:

This method decodes and returns a string from buffer data encoded using the specified
character set encoding.

Let's take an example:

File: main.js

1. buf = new Buffer(26);


2. for (var i = 0 ; i < 26 ; i++) {
3. buf[i] = i + 97;
4. }
5. console.log( buf.toString('ascii')); // outputs: abcdefghijklmnopqrstuvwxyz
6. console.log( buf.toString('ascii',0,5)); // outputs: abcde
7. console.log( buf.toString('utf8',0,5)); // outputs: abcde
8. console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde

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.

The process is a global object, an instance of EventEmitter, can be accessed from


anywhere.

Node.js Process Properties


A list of commonly used Node.js process properties are given below.

Property Description

arch returns process architecture: 'arm', 'ia32', or 'x64'

args returns commands line arguments as an array

env returns user environment

pid returns process id of the process

platform returns platform of the process: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'

release returns the metadata for the current node release

version returns the node version

versions returns the node version and its dependencies

Node.js Process Properties Example


Let's see the simple process example to print architecture, pid, platform and
version of the process.

File: process_example1.js

1. console.log(`Process Architecture: ${process.arch}`);


2. console.log(`Process PID: ${process.pid}`);

37
Shri V J Modha College of IT
Unit - 1
3. console.log(`Process Platform: ${process.platform}`);
4. console.log(`Process Version: ${process.version}`);

Open Node.js command prompt and run the following code:

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. process.argv.forEach((value, index, array) => {


2. console.log(`${index}: ${value}`);
3. });

Open Node.js command prompt and run the following code:

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

cwd() returns path of current working directory

hrtime() returns the current high-resolution real time in a [seconds,


nanoseconds] array

memoryUsage() returns an object having information of memory usage.

process.kill(pid[, is used to kill the given pid.


signal])

uptime() returns the Node.js process uptime in seconds.

Node.js Process Functions Example


Let's see the process example to print current working directory and uptime of the
process.

File: process_example3.js

1. console.log(`Current directory: ${process.cwd()}`);


2. console.log(`Uptime: ${process.uptime()}`);

Open Node.js command prompt and run the following code:

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

You might also like