0% found this document useful (0 votes)
43 views

Chapter One Introduction Node Js

This document provides an introduction and overview of Node.js. It discusses that Node.js is a JavaScript runtime environment built on Chrome's V8 engine that allows JavaScript to be used for server-side scripting. The document outlines the history of Node.js, its key features like being asynchronous and event-driven, who uses Node.js like LinkedIn, where it can be used like for I/O bound applications, and how to set up the Node.js environment and create a first application.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Chapter One Introduction Node Js

This document provides an introduction and overview of Node.js. It discusses that Node.js is a JavaScript runtime environment built on Chrome's V8 engine that allows JavaScript to be used for server-side scripting. The document outlines the history of Node.js, its key features like being asynchronous and event-driven, who uses Node.js like LinkedIn, where it can be used like for I/O bound applications, and how to set up the Node.js environment and create a first application.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

JUST UNIVERSITY

Ch01
Introduction to Node js

Eng. Abdirahman Abukar Mohamed (Eng Baabale)

1
Chapter Outline
 What is Node js?

 History of Node js

 Features of Node.js

 Who Uses Node.js?

 Where to Use Node.js?

 Node.js - Environment Setup

 Node.js - First Application

 Normal Functions and function Expression

 Basic syntax and Concept of Global Objects


2 2
Introduction To Node js
• Node.js is a server-side platform built on
Google Chrome's JavaScript Engine (V8
Engine).
• Node.js is an open source, cross-platform
runtime environment for developing server-
side and networking applications. Node.js
applications are written in JavaScript and
c++, and can be run within the Node.js
runtime on OS Microsoft Windows, and
Linux.

3 3
Introduction To Node js
• Node.js It is a popular tool for almost any kind of
project!
• Node.js runs the JavaScript engine, the core of Google
Chrome, outside of the browser. This allows Node.js
to be very performing.
• Node.js also provides a rich library of various
JavaScript modules which simplifies the development
of web applications using Node.js to a great extent.
Node.js = Runtime Environment + JavaScript Library

4
History of Node
• Node. js was written initially by Ryan
Dahl in 2009, about thirteen years
after the introduction of the first
server-side JavaScript environment,
Netscape's LiveWire Pro Web. The
initial release supported only Linux
and Mac OS . Its development and
maintenance was led by Dahl and later
sponsored by Joyent.
• Written in: C++, JavaScript

Ryan Dahl, creator of Node.js,


in 2010

5
Features of Node.js

Following are some of the important features that


make Node.js the first choice of software architects.
Asynchronous and Event Driven − All APIs of
Node.js library are asynchronous, that is, non-
blocking. It essentially means 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.
6
Continue…
• Very Fast − Being built on Google Chrome's V8
JavaScript Engine, Node.js library is very fast in code
execution.
• Single Threaded but Highly Scalable − Node.js uses
a single threaded model with event looping. Event
mechanism helps the server to respond in a non-
blocking way and makes the server highly scalable
as opposed to traditional servers which create
limited threads to handle requests. Node.js uses a
single threaded program and the same program can
provide service to a much larger number of requests
than traditional servers like Apache HTTP Server.
7
Continue…
• No Buffering − Node.js applications never buffer
any data. These applications simply output the
data in chunks.

8
Why Should You Use Node.js?
There are multiple reasons as to why you should use
Node.js. Some of the advantages of Node.js are listed
below:
Using Node.js enables complete JavaScript stack
creation to be coordinated, which guarantees the
program’s rate and efficiency.
It is a real masterpiece of Node.js’ programming world
Node.js because it encourages you to create
applications that could effortlessly evolve with your
organization. Node.js operates best in systems that use
the design of small services, where functionality and
versatility can be accomplished rapidly and effortlessly.

9
What Should You Knowing Node.js?
• Knowing JavaScript provides a strong beginning
with Node.js for a programmer. You must recognize
the concepts of back-end designing, but
understanding the coding language can simplify
stuff a lot.
• As an open-source task, Node.js promotes
cooperation and innovations targeted at developing
and adopting the software. It is the goal of its Core
for the constant growth and advancement of
Node.js.
• Node.js helps reduce your company’s expenses,
which is one of the main reasons to use Node.js.
10
Importance of Node Js
• The following diagram depicts some important
parts of Node.js which we will discuss in detail in
the subsequent chapters.

11
Advantage of Node js

12
Disadvantage of Node js

13
JS Vs Node

14
Who Uses Node.js?
• The companies uses node js are includes eBay,
General Electric, GoDaddy, Microsoft, PayPal, Uber,
Wikipins, Yahoo!, and Yammer to name a few.
• LinkedIn - LinkedIn is using Node.js to power their
Mobile Servers, which powers the
• iPhone, Android, and Mobile Web products.
• Projects, Applications, and Companies Using Node

15
Where to Use Node.js?
• Following are the areas where Node.js is proving
itself as a perfect technology partner.
• I/O bound Applications
• Data Streaming Applications
• Data Intensive Real-time Applications (DIRT)
• JSON APIs based Applications
• Single Page Applications
Where Not to Use Node.js? Open Discussion
• It is not advisable to use Node.js for CPU intensive
applications.
16
When to not use Node.js
• Node.js can be used for a lot of applications with
various purpose, the only scenario where it
• should not be used is if there are long processing
times which is required by the application.
• Node is structured to be single threaded. If any
application is required to carry out some long
running calculations in the background. So if the
server is doing some calculation, it won't be able to
process any other requests. As discussed above,
Node.js is best when processing needs less
dedicated CPU time.

17
Node.js - Environment Setup

• To start building your Node.js applications, the first


step is the installation of the node.js framework. The
Node.js framework is available for a variety of
operating systems right from Windows to Ubuntu
and OS X. Once the Node.js framework is installed
you can start building your first Node.js
applications. Download & Install Node.js
• Node.js also has the ability to embedded external
functionality or extended functionality by making
use of custom modules. These modules have to be
installed separately. An example of a module is the
MongoDB module which allows you to work with
MongoDB databases from your Node.js application
18
How to install node.js
• The first steps in using Node.js is the installation of the Node.js
libraries on the client system.
• To perform the installation of Node.js, perform the below
• Step 1) Go to the site https://nodejs.org/en/download/ and download
the necessary binary files.

19
Continue….
• Step 2) Double click on the downloaded .msi file to
start the installation. Click the Run button
• in the first screen to begin the installation.

20
How to create First project
• Node.js scripts are created with the js file extension.
Remember that Node.js is not a programming
language. All the code in this course is JavaScript
code, which is why the js extension is used ,You can
run a Node.js script using the node command. Open
up a new terminal window and navigate to the
directory where the script lives. From the terminal, for
short ctrl + ~
21
Node.js Command Line Options

• There is a wide variety of command line options in


Node.js. These options provide multiple ways to
execute scripts and other helpful run-time options.
• Let's see the list of Node.js command line options:
Index Option Description

1. v, --version It is used to print node's version.


2. -h, --help It is used to print node command line
options.

3. -e, --eval "script" It evaluates the following argument as


JavaScript. The modules which are
predefined in the REPL can also be
used in script.

4. -p, --print "script" It is identical to -e but prints the result.

5. -c, --check Syntax check the script without


executing.
Continue…
6. -i, --interactive It opens the REPL even if stdin
does not appear to be a terminal.
7. -r, --require module It is used to preload the specified
module at startup. It follows
require()'s module resolution rules.
Module may be either a path to a
file, or a node module name.
8. --no-deprecation Silence deprecation warnings.
9. --trace-deprecation It is used to print stack traces for
deprecations.
10. --throw-deprecation It throws errors for deprecations.
11. --no-warnings It silence all process warnings
(including deprecations).
12. --trace-warnings It prints stack traces for process
warnings (including deprecations).
Node.js REPL

• The term REPL stands for Read Eval Print and Loop. It specifies a computer
environment like a window console or a Unix/Linux shell where you can enter the
commands and the system responds with an output in an interactive mode.

• REPL Environment

• The Node.js or node come bundled with REPL environment. Each part of the

REPL environment has a specific work.

• Read: It reads user's input; parse the input into JavaScript data-structure and stores

in memory.

• Eval: It takes and evaluates the data structure.


Node.js REPL Commands

Commands Description

ctrl + c It is used to terminate the current command.

ctrl + c twice It terminates the node repl.

ctrl + d It terminates the node repl.

up/down keys It is used to see command history and modify previous


commands.

tab keys It specifies the list of current command.

.help It specifies the list of all commands.

.break It is used to exit from multi-line expressions.

.clear It is used to exit from multi-line expressions.

.save filename It saves current node repl session to a file.

.load filename It is used to load file content in current node repl session.
Starting
• There can be console-based and web-based node.js
applications.

• Below is an example script stored in a file named


index.js.

• console.log('Hello Node.js!');

27
Normal Functions and function
Expression
• A function declaration tells the compiler about a function's
name, return type, and parameters. A function definition
provides the actual body of the function
• A function expression is very similar to and has almost the
same syntax as a function declaration (see function
statement for details).
• The function in function declaration can be accessed before
and after the function definition. The function in function
declaration can be accessed only after the function
definition.
• Function declarations are hoisted while Function
expressions are not hoisted.

28
Continue..
• //normal function
• function greet(){
• console.log('assalamu alykum');
• }
greet();

//function expression

var sayby= function(){
• console.log('macasalaama');
• }

sayby();

29
Functions hoisted and not hoisted
• //normal function
• greet();
• function greet(){
• console.log('assalamu alykum');
• }
//function expression
• sayby();
• var sayby= function(){
• console.log('macasalaama');
• }

30
Continue….
• const test = (name) =>{
• console.log(`hello , ${name}`);
•}

test('ali');
• test('osman')

31
Global objects
• Node. js global objects are global in nature and they
are available in all modules. These objects are
modules, functions, strings etc. Some of these
objects aren't actually in the global scope but in the
module scope.
• A list of Node.js global objects are given below:
• dirname
• __filename
• Console
• Process

32
Global Objects
• Buffer
• setImmediate(callback[, arg][, ...])
• setInterval(callback, delay[, arg][, ...])
• setTimeout(callback, delay[, arg][, ...])
• clearImmediate(immediateObject)
• clearInterval(intervalObject)
• clearTimeout(timeoutObject)

33
Node.js __dirname

• it is a string. It specifies the name of the directory


that currently contains the code.
console.log(__dirname);

• Output

34
Node.js __filename

• It specifies the filename of the code being executed.


This is the resolved absolute path of this code file.
The value inside a module is the path to that module
file.
• console.log(__filename);
• Output

35
setTimeout() method

• setTimeout() method: It is a global function used to run


a callback function after at least delay in milliseconds.
• Example :
setTimeout(() => {
• console.log("time wa kadhacay")

}, 3000);

36
clearTimeout() method
• clearTimeout() method: The clearTimeout() method is used to

cancel or stop a timeout that was set with setTimeout() method.

The timeoutObj is the object returned by setTimeout() method.


• setTimeout(() => {
• console.log("time wa kadhacay")
• clearTimeout(int);
• }, 3000);

const int = setTimeout(() => {
• console.log("wan tirianaya ila kajojiso");
• },1000);

37
setInterval() method
• setInterval() The setInterval() function is
commonly used to set a delay for functions that are
executed again and again, such as animations.
• The setInterval() method helps us to repeatedly
execute a function after a fixed delay

38
Node.js Errors

• The Node.js applications generally face four types of errors:

• Standard node js errors i.e. <EvalError>, <SyntaxError>,


<RangeError>, <ReferenceError>, <TypeError>,
<URIError> etc.

• System errors

• User-specified errors

• Assertion errors

39
Node.js ReferenceError Example 1
• standard Node js error :
• // Throws with a ReferenceError because b is unde
fined
• try {
• const a = 1;
• const c = a + b;
• } catch (err) {
• console.log(err);
• }

40
RangeError
• A RangeError is thrown when trying to pass a
value as an argument to a function that does not
allow a range that includes the value.
• let a = [];
• a.length = a.length - 5;
• console.log(a);

41
TypeError
• TypeError indicates that a passed argument is not of the
appropriate type. This method is used liberally throughout the
built-in Node API modules, and should also be used within your
own custom code to perform type checking at the top of your
functions and methods.
• let num = 11;
• try{
• num.toUpperCase();
• }
• catch (err){
• console.log(err);
• }

42
END
43

You might also like