0% found this document useful (0 votes)
11 views14 pages

Unit 4

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)
11 views14 pages

Unit 4

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/ 14

Unit-4

Node.js Web Server


In this section, we will learn how to create a simple Node.js web server and handle
HTTP requests.

To access web pages of any web application, you need a web server. The web
server will handle all the http requests for the web application e.g IIS is a web
server for ASP.NET web applications and Apache is a web server for PHP or Java
web applications.

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.

Create Node.js Web Server


Node.js makes it easy to create a simple web server that processes incoming
requests asynchronously.

The following example is a simple Node.js web server contained in server.js file.

server.js

var http = require('http'); // 1 - Import Node.js core module


var server = http.createServer(function (req, res) { // 2 - creating server
//handle incomming requests here..

});

server.listen(5000); //3 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

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

1
Shri V J Modha College of IT
Unit-4
listening to incoming requests on port 5000. You can specify any unused port
here.

Run the above web server by writing node server.js command in command prompt
or terminal window and it will display message as shown below.

C:\> node server.js

Node.js web server at port 5000 is running..

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.

2
Shri V J Modha College of IT
Unit-4
Handle HTTP Request
The http.createServer() method includes request and response parameters
which is supplied by Node.js. The request object can be used to get information
about the current HTTP request e.g., url, request header, and data. The response
object can be used to send a response for a current HTTP request.

The following example demonstrates handling HTTP request and response in


Node.js.

server.js

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) { //create web server


if (req.url == '/') { //check the URL of the current request

// set response header


res.writeHead(200, { 'Content-Type': 'text/html' });

// set response content


res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();

}
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") {

res.writeHead(200, { 'Content-Type': 'text/html' });


res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();

3
Shri V J Modha College of IT
Unit-4
else
res.end('Invalid Request!');

});

server.listen(5000); //6 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')

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.

Now, run the above web server as shown below.

C:\> node server.js

Node.js web server at port 5000 is running..

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

You should see the following response.

HTTP/1.1 200 OK

Content-Type: text/plain

Date: Tue, 8 Sep 2015 03:05:08 GMT

4
Shri V J Modha College of IT
Unit-4
Connection: keep-alive

This is home page.

For Windows users, point your browser to http://localhost:5000 and see the
following result.

Node.js Web Server Response

The same way, point your browser to http://localhost:5000/student and see the
following result.

5
Shri V J Modha College of IT
Unit-4

Node.js Web Server Response

It will display "Invalid Request" for all requests other than the above URLs.

Sending JSON Response


The following example demonstrates how to serve JSON response from the
Node.js web server.

server.js
Copy
var http = require('http');

var server = http.createServer(function (req, res) {

if (req.url == '/data') { //check the URL of the current request


res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ message: "Hello World"}));
res.end();
}
});

server.listen(5000);

console.log('Node.js web server at port 5000 is running..')

6
Shri V J Modha College of IT
Unit-4
So, this way you can create a simple web server that serves different responses.

7
Shri V J Modha College of IT
Unit-4
Node.js File System
Node.js includes fs module to access physical file system. The fs module is
responsible for all the asynchronous or synchronous file I/O operations.

Let's see some of the common I/O operation examples using fs module.

Reading a File
Use the fs.readFile() method to read the physical file asynchronously.

fs.readFile(fileName [,options], callback)

Parameter Description:

• filename: Full path and name of the file as a string.


• options: The options parameter can be an object or string which can include
encoding and flag. The default encoding is utf8 and default flag is "r".
• callback: A function with two parameters err and fd. This will get called
when readFile operation completes.

The following example demonstrates reading existing TestFile.txt asynchronously.

Example: Reading a File

var fs = require('fs');

fs.readFile('TestFile.txt', function (err, data) {


if (err)
throw err;

console.log(data);
});

The above example reads TestFile.txt (on Windows) asynchronously and executes
callback function when read operation completes. This read operation either
throws an error or completes successfully. The err parameter contains error
information if any. The data parameter contains the content of the specified file.

8
Shri V J Modha College of IT
Unit-4
The following is a sample TextFile.txt file.

TextFile.txt

This is test file to test fs module of Node.js

Now, run the above example and see the result as shown below.

C:\> node server.js

This is test file to test fs module of Node.js

Use the fs.readFileSync() method to read file synchronously, as shown below.

Example: Reading File Synchronously

var fs = require('fs');

var data = fs.readFileSync('dummyfile.txt', 'utf8');


console.log(data);

9
Shri V J Modha College of IT
Unit-4
Writing a File
Use the fs.writeFile() method to write data to a file. If file already exists then it
overwrites the existing content otherwise it creates a new file and writes data
into it.Signature:

fs.writeFile(filename, data[, options], callback)

Parameter Description:

• filename: Full path and name of the file as a string.


• Data: The content to be written in a file.
• options: The options parameter can be an object or string which can include
encoding, mode and flag. The default encoding is utf8 and default flag is "r".
• callback: A function with two parameters err and fd. This will get called when
write operation completes.

The following example creates a new file called test.txt and writes "Hello World"
into it asynchronously.

Example: Creating & Writing a File

var fs = require('fs');

fs.writeFile('test.txt', 'Hello World!', function (err) {


if (err)
console.log(err);
else
console.log('Write operation complete.');
});

In the same way, use the fs.appendFile() method to append the content to an
existing file.

Example: Append Content to a File

var fs = require('fs');

fs.appendFile('test.txt', 'Hello World!', function (err) {


if (err)

10
Shri V J Modha College of IT
Unit-4
console.log(err);
else
console.log('Append operation complete.');
});

Open File
Alternatively, you can open a file for reading or writing using the fs.open() method.

fs.open(path, flags[, mode], callback)

Parameter Description:

• path: Full path with name of the file as a string.


• Flag: The flag to perform operation
• Mode: The mode for read, write or readwrite. Defaults to 0666 readwrite.
• callback: A function with two parameters err and fd. This will get called when
file open operation completes.

Flags

The following table lists all the flags which can be used in read/write operation.

Flag Description

r Open file for reading. An exception occurs if the file does not exist.

r+ Open file for reading and writing. An exception occurs if the file does not exist.

rs Open file for reading in synchronous mode.

rs+ Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about
using this with caution.

w Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

wx Like 'w' but fails if path exists.

w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).

11
Shri V J Modha College of IT
Unit-4
Flag Description

wx+ Like 'w+' but fails if path exists.

a Open file for appending. The file is created if it does not exist.

ax Like 'a' but fails if path exists.

a+ Open file for reading and appending. The file is created if it does not exist.

ax+ Like 'a+' but fails if path exists.

The following example opens an existing file and reads its content.

Example:File open and read

var fs = require('fs');

fs.open('TestFile.txt', 'r', function (err, fd) {

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

var buffr = new Buffer(1024);

fs.read(fd, buffr, 0, buffr.length, 0, function (err, bytes) {

if (err) throw err;

// Print only read bytes to avoid junk.


if (bytes > 0) {
console.log(buffr.slice(0, bytes).toString());
}

// Close the opened file.


fs.close(fd, function (err) {
if (err) throw err;
});
});
});

12
Shri V J Modha College of IT
Unit-4
Delete File
Use the fs.unlink() method to delete an existing file.

fs.unlink(path, callback);

The following example deletes an existing file.

Example:Delete a File

var fs = require('fs');

fs.unlink('test.txt', function () {
console.log('File Deleted Successfully.');
});

Important method of fs module


Method Description

fs.readFile(fileName [,options], callback) Reads existing file.

fs.writeFile(filename, data[, options], callback) Writes to the file. If file exists then overwrite the content
otherwise creates new file.

fs.open(path, flags[, mode], callback) Opens file for reading or writing.

fs.rename(oldPath, newPath, callback) Renames an existing file.

fs.chown(path, uid, gid, callback) Asynchronous chown.

fs.stat(path, callback) Returns fs.stat object which includes important file


statistics.

fs.link(srcpath, dstpath, callback) Links file asynchronously.

fs.unlink(path, callback); Delete a file.

fs.symlink(destination, path[, type], callback) Symlink asynchronously.

fs.rmdir(path, callback) Renames an existing directory.

13
Shri V J Modha College of IT
Unit-4
Method Description

fs.mkdir(path[, mode], callback) Creates a new directory.

fs.readdir(path, callback) Reads the content of the specified directory.

fs.utimes(path, atime, mtime, callback) Changes the timestamp of the file.

fs.exists(path, callback) Determines whether the specified file exists or not.

fs.access(path[, mode], callback) Tests a user's permissions for the specified file.

fs.appendFile(file, data[, options], callback) Appends new content to the existing file.

14
Shri V J Modha College of IT

You might also like