NodeJs 1
NodeJs 1
NodeJs 1
Application of JavaScript
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
JavaScript Example
1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>
Functions
A function is a block of code which will be executed only if it is called. If you
have a few lines of code that needs to be used several times, you can create a
function including the repeating lines of code and then call the function
wherever you want.
Types of Functions
o Pre-defined Functions
o User-defined Functions
Syntax:
function functionname()
<html>
<head>
<title>Functions!!!</title>
<script type="text/javascript">
function myFunction()
{
document.write("This is a simple function.<br />");
}
myFunction();
</script>
</head>
<body>
</body>
</html
Syntax:
If the function was invoked from a statement, JavaScript will "return" to execute
the code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to
the "caller":
Example
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Introduction to NodeJs
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.
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 makes it lightweight and efficient, perfect for data-
intensive real-time applications that run across distributed devices
Features of Node.js
Following is a list of some important features of Node.js that makes it the first
choice of software architects.
Node Package Manager (NPM) is a command line tool that installs, updates
or uninstalls Node.js packages in your application. It is also an online
repository for open-source Node.js packages. The node community around
the world creates useful modules and publishes them as packages in this
repository.
A package contains all the files needed for a module and modules are the
JavaScript libraries that can be included in Node project according to the
requirement of the project. NPM can install all the dependencies of a project
through the package. json file. It can also update and uninstall package
V8
V8 is a C++-based open-source JavaScript engine developed by Google. It
was originally designed for Google Chrome and Chromium-based browsers
(such as Brave) in 2008, but it was later utilized to create Node.js for server-
side coding.
V8 is known to be a JavaScript engine because it takes JavaScript code and
executes it while browsing in Chrome. It provides a runtime environment for
the execution of JavaScript code. The best part is that the JavaScript engine is
completely independent of the browser in which it runs. This is the feature
that led Node.js designers to choose the V8 engine to power the framework,
// Synchronous read
Output:
Asynchronous functions do not block the execution of the program and each
command is executed after the previous command even if the previous command has
not computed the result. The previous command runs in the background and loads
the result once it has finished processing. Thus, these functions are called non-
blocking functions. They take a callback function as the last parameter
// Asynchronous read
if (err) {
return console.error(err);
}
});
Output:
Difference between Asynchronous and Synchronous methods:
Sr.n
Synchronous methods Asynchronous methods
o
These functions take File Descriptor as the These functions take a callback
3.
last argument. function as the last argument.
The REPL has started and is demarcated by the ‘>’ symbol. Various operations can
be performed on the REPL. Below are some of the examples to get familiar with the
REPL environment.
Example: Performing Arithmetical operations in REPL
Streams
of data handler that enable reading and writing data in chunks instead
const fs = require('fs');
readableStream.pipe(writableStream);
Buffer
Buffers are another important concept in Node.js that provide a way to
handle binary data in memory. Buffers are essentially arrays of integers that
represent raw binary data. They can be used to store data in memory, read
data from files or network sockets, and manipulate data in various ways.
In Node.js, Buffers are a built-in data type that are part of the ‘Buffer’
module. Buffers can be created in several ways, such as from a string, an
array, or a buffer from another source.
Once we have a Buffer object, we can manipulate the data in various ways,
such as reading or writing individual bytes, copying data to another buffer,
or converting the buffer to a string.
console.log(buffer3.toString());
Node.js provides capabilities to create your own web server which will handle
HTTP requests asynchronously. You can use IIS or Apache to run Node.js web
application but it is recommended to use Node.js web server.
The following example is a simple Node.js web server contained in server.js file.
});
In the above example, we import the http module using require() function. The
http module is a core module of Node.js, so no need to install it using NPM. The
next step is to call createServer() method of http and specify callback function
with request and response parameter. Finally, call listen() method of server
object which was returned from createServer() method with port number , to
start listening to incoming requests on port 5000. You can specify any unused port
here.
This is how you create a Node.js web server using simple steps. Now, let's see how
to handle HTTP request and send response in Node.js web server.
442.5K
}
else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student
Page.</p></body></html>');
res.end();
}
else if (req.url == "/admin") {
}
else
res.end('Invalid Request!');
});
In the above example, req.url is used to check the url of the current request and
based on that it sends the response. To send a response, first it sets the response
header using writeHead() method and then writes a string as a response body
using write() method. Finally, Node.js web server sends the response using end()
method.
To test it, you can use the command-line program curl, which most Mac and Linux
machines have pre-installed.
curl -i http://localhost:5000
Content-Type: text/plain
Connection: keep-alive
Events
Every action on a computer is an event. Like when a connection is made or a
file is opened.
Node.js EventEmitter
Node.js allows us to create and handle custom events easily by using events
module. Event module includes EventEmitter class which can be used to raise and
handle custom events.
The following example demonstrates EventEmitter class for raising and handling a
custom event.
Example: Raise and Handle Node.js events
Copy
// get the reference of EventEmitter class of events module
var events = require('events');
// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter
example.');
In the above example, we first import the 'events' module and then create an object
of EventEmitter class. We then specify event handler function using on() function.
The on() method requires name of the event to handle and callback function which
is called when an event is raised.
Process
The process module in Node.js allows us to get information related to the
node and control its behavior. This module is, and we can use it to get
information such as process ID, version, release, CPU usage, and uptime
globally available or perform actions such as killing processes, setting uid,
setting groups, unmasking, etc.
example 1
// Including the module into out project
var process = require('process');
// Viewing the current working directory
console.log('Working directory --> ' + process.cwd());
// Viewing the version of process we are using
console.log('Process version --> ' + process.version);
// Viewing the type of OS we are using
console.log('Current OS --> ' + process.platform);
// Viewing the arguments passed
console.log('Arguments --> ', process.argv);
// Viewing the Feature Object
console.log('Feature Property: \n', process.features);