Module III
Module III
FILE HANDLING
AND HTTP WEB
SERVER
Detailed Contents
File Path(Manipulation)
A. Normalizing Path
B. Joining Path
C. Resolving Path
D. Finding relative path between two absolute paths
E. Extracting components of path
F. Determining the Existence of path
A) NORMALIZING PATH
? The path.normalize() method resolves the
specified path, fixing '\\\\' etc.
? Syntax-path.normalize(path);
? Parameter value:-path-Required a string. The
path we want to normalized.
B) JOINING PATH
? By using path.join(), you can concatenate path strings. You
can concatenate as many as you like,passing all of them as
consecutive arguments.
? Syntax-path.join(paths);
? Parameter Value-paths-Series of path segments to join into
one path.
? The path.resolve()
C) RESOLVING PATH method is used to resolve a sequence of path-
segments to an absolute path.
? It works by processing the sequence of paths from right to left,
prepending each of the paths until the absolute path is created. The
resulting path is normalized and trailing slashes are removed as
required.
? If no path segments are given as parameters, then the absolute path
of the current working directory is used.
? Syntax- path.resolve(…[path]…)
D) FINDING RELATIVE PATH
BETWEEN TWO PATHS
? The path.relative() method is used to find the relative path from
a given path to another path based on the current working
directory.
? If both the given paths are the same, it would resolve to a zero-
length string.
? Syntax: path.relative( from, to )
? Parameters: This method accept two parameters as mentioned
above and described below:
? from: It is the file path that would be used as base path.
? to: It is the file path that would be used to find the relative path.
E) EXTRACTING COMPONENTS OF PATH
a) Parent directory component:-
? The path.dirname() method returns the directories of a file path.
? Syntax-path.dirname(path);
? Parameter-path-Required. The file path to search in.
b) File Name form file path:
? The path.basename() method returns the filename part of a file
path
? Syntax-path.basename(path, extension);
c) Extension Name:
? The path.extname() method returns the extension of a file path.
? Syntax-path.extname(path);
F) DETERMINING THE EXISTENCE OF PATH
? To check if a file exists in the file system is by using the
fs.module's fs.existsSync() method. It returns true if the
path exists, false otherwise
fs Module
? The fs module is where all the file query and
manipulation functions are stored. With these
functions, we can query file statistics, as well as
open, read from, write to, and close files. We can
require the fs module like this:
var fs = require('fs');
SYNCHRONOUS AND
ASYNCHRONOUS(Read Write file)
BUFFER OPERATION
? Buffer Creation
? Buffer Read
? Buffer write
STREAM
? Streams are objects that let us read data from a source or write data to a destination in
continuous fashion.
In Node.js, there are four types of streams −
Duplex − Stream which can be used for both read and write operation.
Transform − A type of duplex stream where the output is computed based on input.
? Each type of Stream is an EventEmitter instance and throws several events at different instance
of times. For example, some of the commonly used events are −
error − This event is fired when there is any error receiving or writing data.
finish − This event is fired when all the data has been flushed to underlying system.
Stream Operation
Read
Write
OPENING A FILE
? Create a new, empty file using the open() method
? Syntax
var fs = require('fs');
fs.open('/path/to/file', ‘flag', function(err, fd)
{ // got fd file descriptor });
o The first argument to fs.open() is the file path. The second
argument contains the flags, which indicate the mode with which
the file should open. The flags can be r, r+, w, w+, a, or a+.
? r—Opens the text file for reading. The stream is positioned at the
beginning of the file.
? r+—Opens the file for reading and writing. The stream is
positioned at the beginning of the file.
? w—Truncates the file to zero length or creates a text file for
writing. The stream is positioned at the beginning of the file.
? w+—Opens the file for reading and writing. The file is created if it
does not exist. Otherwise it is truncated. The stream is positioned at
the beginning of the file.
? a—Opens the file for writing. The file is created if it does not exist.
The stream is positioned at the end of the file. Subsequent writes to
the file will always end up at the current end of file.
? a+—Opens the file for reading and writing. The file is created if it
does not exist. The stream is positioned at the end of the file.
Subsequent writes to the file will always end up at the current end
of file.
File will be created if not present
READING FROM A FILE
? Syntax
fs.readFile(file, [encoding], [callback]);
? UTF-8 encoder/decoder: it can encode/decode any scalar
Unicode code point values.
WRITING TO A FILE
? Syntax:
fs.writeFile(filename, data, [encoding], [callback]
CLOSING A FILE
Task
1) Delete File
Use fs.unlink() method to delete an existing file.
Syntax
fs.unlink(path, callback);
var fs = require('fs');
fs.unlink('test.txt', function ()
{ console.log('write operation
complete.');
});
Task2
Append file
fs.appendFile(file, data[, options],
callback)
var fs = require('fs');
fs.appendFile('test.txt', 'Hello World!', function(err) {
if (err)
console.log(err);
else
console.log('Append operation complete.'); });
HTTP WEB SERVER:
? To access web pages of any web application, we need a web server.
The web server will handle all the http requests for the web
application.
? Node.js provides capabilities to create your own web server which
will handle HTTP requests asynchronously.
CREATE NODE.JS WEB SERVER
HTTP REQUEST/RESPONSE
OBJECT
Pipe Function
var fs = require('fs');
require('http').createServer(function(req, res)
{
res.writeHead(200, {'Content-Type': ‘XYZ});
var rs = fs.createReadStream('test.mp4');
rs.pipe(res);
}).listen(4000)