0% found this document useful (1 vote)
918 views

Lab 1 - Node - Js

The document provides an overview of Node.js, including what it is, why it is used, its key features and capabilities. Node.js is an open-source and cross-platform JavaScript runtime environment for developing server-side web applications. It allows non-blocking asynchronous programming which makes it very efficient. Common uses of Node.js include building APIs, real-time apps, IoT backends, microservices and more. The document then demonstrates how to get started with Node.js by creating a simple "Hello World" app and running it on a local server.

Uploaded by

Vidhi jain
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
918 views

Lab 1 - Node - Js

The document provides an overview of Node.js, including what it is, why it is used, its key features and capabilities. Node.js is an open-source and cross-platform JavaScript runtime environment for developing server-side web applications. It allows non-blocking asynchronous programming which makes it very efficient. Common uses of Node.js include building APIs, real-time apps, IoT backends, microservices and more. The document then demonstrates how to get started with Node.js by creating a simple "Hello World" app and running it on a local server.

Uploaded by

Vidhi jain
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Node.

js
• Node.js is an open-source, cross-platform runtime
environment used for development of server-side web
applications. Node.js applications are written in JavaScript
and can be run on a wide variety of operating systems.
• Node.js is a very powerful JavaScript-based platform built
on Google Chrome's JavaScript V8 Engine. It is used to
develop I/O intensive web applications like video
streaming sites, single-page applications, and other web
applications. Node.js is open source, completely free, and
used by thousands of developers around the world.
Why Node.js?
• A common task for a web server can be to open a file on the server and
return the content to the client.
• Here is how PHP or ASP handles a file request:
• Sends the task to the computer's file system.
• Waits while the file system opens and reads the file.
• Returns the content to the client.
• Ready to handle the next request.

• Here is how Node.js handles a file request:


• Sends the task to the computer's file system.
• Ready to handle the next request.
• When the file system has opened and read the file, the server returns the
content to the client.
• Node.js eliminates the waiting, and simply continues with the next request.
• Node.js runs single-threaded, non-blocking, asynchronously programming,
which is very memory efficient.
• What Can Node.js Do?
• Node.js can generate dynamic page content
• Node.js can create, open, read, write, delete,
and close files on the server
• Node.js can collect form data
• Node.js can add, delete, modify data in your
database
• Getting Started -
• Once you have downloaded and installed Node.js on
your computer, let's try to display "Hello World" in a
web browser.
• Create a Node.js file named "myfirst.js", and add the
following code:

var http = require('http');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
• Save the file on your computer: C:\Users\Your
Name\myfirst.js
• The code tells the computer to write "Hello World!" if
anyone (e.g. a web browser) tries to access your
computer on port 8080.
• Open the commmand prompt and run the file as
follows –
• C:\Users\Your Name>node myfirst.js
• Now, your computer works as a server!
• If anyone tries to access your computer on port 8080,
they will get a "Hello World!" message in return!
• Start your internet browser, and type in the address: 
http://localhost:8080
Node.js Modules

• What is a Module in Node.js?


• Consider modules to be the same as JavaScript libraries.
• A set of functions you want to include in your application.
• Built-in Modules
• Node.js has a set of built-in modules which you can use
without any further installation.
• Include Modules
• To include a module, use the require() function with the
name of the module:
• var http = require('http');
• Create Your Own Modules
• You can create your own modules, and easily include them in
your applications.
• The following example creates a module that returns a date and
time object:
• Example
• Create a module that returns the current date and time:-

exports.myDateTime = function () {
return Date();
};

• Use the exports keyword to make properties and methods


available outside the module file.
• Save the code above in a file called "myfirstmodule.js"
• Include Your Own Module
• Now you can include and use the module in any of your
Node.js files.
• Example

var http = require('http');


var dt = require('./myfirstmodule');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " +
dt.myDateTime());
res.end();
}).listen(8080);
• Notice that we use ./ to locate the module,
that means that the module is located in the
same folder as the Node.js file.
• Save the code above in a file called
"demo_module.js", and initiate the file:
• Initiate demo_module.js:
• C:\Users\Your Name>node demo_module.js
• If you have followed the same steps on your
computer, you will see the same result as the
example: http://localhost:8080
• Node.js HTTP Module -
• The Built-in HTTP Module-
• Node.js has a built-in module called HTTP, which allows
Node.js to transfer data over the Hyper Text Transfer
Protocol (HTTP).
• To include the HTTP module, use the require() method:
• var http = require('http');
• Node.js as a Web Server
• The HTTP module can create an HTTP server that listens
to server ports and gives a response back to the client.
• Use the createServer() method to create an HTTP
server:
• Example
• var http = require('http');

//create a server object:


http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
• The function passed into the http.createServer() method, will
be executed when someone tries to access the computer on
port 8080.
• Save the code above in a file called "demo_http.js", and
initiate the file:
• Initiate demo_http.js:
• C:\Users\Your Name>node demo_http.js
• Add an HTTP Header
• If the response from the HTTP server is supposed to be displayed
as HTML, you should include an HTTP header with the correct
content type:
• Example
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);

• The first argument of the res.writeHead() method is the status


code, 200 means that all is OK, the second argument is an object
containing the response headers.
• Read the Query String
• The function passed into the http.createServer() has a
req argument that represents the request from the
client, as an object (http.IncomingMessage object).
• This object has a property called "url" which holds the
part of the url that comes after the domain name:-

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(req.url);
res.end();
}).listen(8080);
• Save the code above in a file called "demo_http_url.js" and
initiate the file:
• Initiate demo_http_url.js:
• C:\Users\Your Name>node demo_http_url.js
• If you have followed the same steps on your computer, you
should see two different results when opening these two
addresses:
• http://localhost:8080/summer
• Will produce this result:
• /summer

• http://localhost:8080/winter
• Will produce this result:
• /winter
• Split the Query String -
• There are built-in modules to easily split the query string into readable parts, such as the URL module.
• Example
• Split the query string into readable parts:

var http = require('http');


var url = require('url');

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);

• (
• url.parse(urlStr, parseQueryString=false, slashesDenoteHost=false) #
• Take a URL string, and return an object.
• Pass true as the second argument to also parse the query string using the querystring module.
• Pass true as the third argument to treat //foo/bar as { host: 'foo', pathname: '/bar' }rather
than { pathname: '//foo/bar' }.
• )
• Save the code above in a file called
"demo_querystring.js" and initiate the file:
• Initiate demo_querystring.js:
• C:\Users\Your Name>node
demo_querystring.js
• The address:
• http://localhost:8080/?year=2017&month=Jul
y
• Will produce this result:
• 2017 July
Node.js File System Module

• Node.js as a File Server


• The Node.js file system module allows you to work with the file
system on your computer.
• To include the File System module, use the require() method:
• var fs = require('fs');
• Common use for the File System module:
• Read files
• Create files
• Update files
• Delete files
• Rename files
• Read Files
• The fs.readFile() method is used to read files on
your computer.
• Assume we have the following HTML file (located
in the same folder as Node.js):-
• demofile1.html -
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
• Create a Node.js file that reads the HTML file, and return the content:
• Example

var http = require('http');


var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('test1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}).listen(8080);

• Save the code above in a file called "demo_readfile.js", and initiate the file:
• Initiate demo_readfile.js:
• C:\Users\Your Name>node demo_readfile.js
• If you have followed the same steps on your computer, you will see the same
result as the example: http://localhost:8080
• Create Files
• The File System module has methods for
creating new files:
• fs.appendFile()
• fs.open()
• fs.writeFile()
1- The fs.appendFile() method appends specified
content to a file. If the file does not exist, the file
will be created:
• Example
• Create a new file using the appendFile()
method:
var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function


(err) {
if (err) throw err;
console.log('Saved!');
});
Data **
2- The fs.open() method takes a "flag" as the second
argument, if the flag is "w" for "writing", the specified file
is opened for writing. If the file does not exist, an empty
file is created:
• Example
• Create a new, empty file using the open() method:
var fs = require('fs');

fs.open('mynewfile2.txt', 'w', function (err, file) {


if (err) throw err;
console.log('Saved!');
});
3- The fs.writeFile() method replaces the specified
file and content if it exists. If the file does not
exist, a new file, containing the specified content,
will be created:
• Example
• Create a new file using the writeFile() method:
var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {


if (err) throw err;
console.log('Saved!');
});

• Delete Files
• To delete a file with the File System module,  use
the fs.unlink() method.
• The fs.unlink() method deletes the specified file:
• Example
• Delete "mynewfile2.txt":
var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {


if (err) throw err;
console.log('File deleted!');
});
• Rename Files
• To rename a file with the File System module,  use
the fs.rename() method.
• The fs.rename() method renames the specified file:
• Example
• Rename "mynewfile1.txt" to "myrenamedfile.txt":
• var fs = require('fs');

fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
  if (err) throw err;
  console.log('File Renamed!');
});
Node.js URL Module

• The Built-in URL Module


• The URL module splits up a web address into
readable parts.
• To include the URL module, use
the require() method:
• var url = require('url');
• Parse an address with the url.parse() method,
and it will return a URL object with each part of
the address as properties:
• Example
• Split a web address into readable parts:

var url = require('url');


var adr = 'http://localhost:8080/default.htm?
year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'


console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february'


}
console.log(qdata.month); //returns 'february'
• Node.js File Server
• Now we know how to parse the query string, and in the previous
chapter we learned how to make Node.js behave as a file server.
Let us combine the two, and serve the file requested by the client.
• Create two html files and save them in the same folder as your
node.js files.
• summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
• winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
• Create a Node.js file that opens the requested file and
returns the content to the client. If anything goes
wrong, throw a 404 error:
• demo_fileserver.js:
var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {


var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
• Remember to initiate the file:
• Initiate demo_fileserver.js:
• C:\Users\Your Name>node demo_fileserver.js
• If you have followed the same steps on your computer, you
should see two different results when opening these two
addresses:
• http://localhost:8080/summer.html
• Will produce this result:
• Summer
• I love the sun!
• http://localhost:8080/winter.html
• Will produce this result:
• Winter
• I love the snow!
Node.js NPM

• What is NPM?
• NPM is a package manager for Node.js
packages, or modules if you like.
• www.npmjs.com hosts thousands of free
packages to download and use.
• The NPM program is installed on your
computer when you install Node.js
• What is a Package?
• A package in Node.js contains all the files you need
for a module.
• Modules are JavaScript libraries you can include in
your project.
• Download a Package
• Downloading a package is very easy.
• Open the command line interface and tell NPM to
download the package you want.
• I want to download a package called "upper-case":
• Download "upper-case":
• C:\Users\Your Name>npm install upper-case
• Now you have downloaded and installed your first package!
• NPM creates a folder named "node_modules", where the
package will be placed. All packages you install in the future
will be placed in this folder.
• My project now has a folder structure like this:
• C:\Users\My Name\node_modules\upper-case
• Using a Package
• Once the package is installed, it is ready to use.
• Include the "upper-case" package the same way you include
any other module:
• var uc = require('upper-case');
• Create a Node.js file that will convert the output "Hello
World!" into upper-case letters:
• Example-
var http = require('http');
var uc = require('upper-case');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type':
'text/html'});
res.write(uc("Hello World!"));
res.end();
}).listen(8080);
Node.js Events

• Node.js is perfect for event-driven applications.


• Events in Node.js
• Every action on a computer is an event. Like when a connection
is made or a file is opened.
• Events Module
• Node.js has a built-in module, called "Events", where you can
create-, fire-, and listen for- your own events.
• To include the built-in Events module use the require() method.
• In addition, all event properties and methods are an instance of
an EventEmitter object. To be able to access these properties
and methods, create an EventEmitter object:
• var events = require('events');
var eventEmitter = new events.EventEmitter();
• The EventEmitter Object
• You can assign event handlers to your own events with the EventEmitter object.
• In the example below we have created a function that will be executed when a "scream" event is fired.
• To fire an event, use the emit() method.

var events = require('events');


var eventEmitter = new events.EventEmitter();

//Create an event handler:


var myEventHandler = function () {
console.log('I hear a scream!');
}

//Assign the event handler to an event:


eventEmitter.on('scream', myEventHandler);

//Fire the 'scream' event:


eventEmitter.emit('scream');

• The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to


trigger the event.

You might also like