Tuesday, August 14, 2018

Modules in Node.JS


Modules in  Node.JS



Buffers

  • Creating Buffers

Node Buffer can be constructed in a variety of ways.

Method 1
Following is the syntax to create an uninitiated Buffer of 10 octets:
var buf = new Buffer(10);

Method 2
Following is the syntax to create a Buffer from a given array:
var buf = new Buffer([10, 20, 30, 40, 50]);

Method 3
Following is the syntax to create a Buffer from a given string and optionally encoding type:
var buf = new Buffer("Simply Easy Learning", "utf-8");

Though "utf8" is the default encoding, you can use any of the following encodings "ascii",
"utf8", "utf16le", "ucs2", "base64" or "hex".


1--------Writing to Buffers
Syntax

Following is the syntax of the method to write into a Node Buffer:

buf.write(string[, offset][, length][, encoding])




Parameters
Here is the description of the parameters used:
 string - This is the string data to be written to buffer.
 offset - This is the index of the buffer to start writing at. Default value is 0.
 length - This is the number of bytes to write. Defaults to buffer.length.
 encoding - Encoding to use. 'utf8' is the default encoding.



2----------Reading from Buffers
Syntax
Following is the syntax of the method to read data from a Node Buffer:

buf.toString([encoding][, start][, end])

Parameters
Here is the description of the parameters used:
 encoding - Encoding to use. 'utf8' is the default encoding.
 start - Beginning index to start reading, defaults to 0.
 end - End index to end reading, defaults is complete buffer


3----------Convert Bufferto JSON

Syntax
Following is the syntax of the method to convert a Node Buffer into JSON object:
buf.toJSON()


4-----------Concatenate Buffers
Syntax
Following is the syntax of the method to concatenate Node buffers to a single Node Buffer:
Buffer.concat(list[, totalLength])
Parameters
Here is the description of the parameters used:
 list - Array List of Buffer objects to be concatenated.
 totalLength - This is the total length of the buffers when concatenated.


5----------Compare Buffers
Syntax
Following is the syntax of the method to compare two Node buffers:
buf.compare(otherBuffer);
Parameters
Here is the description of the parameters used:
OtherBuffer - This is the other buffer which will be compared with buf


6-----------Copy Buffer
Syntax
Following is the syntax of the method to copy a node buffer:
buf.copy(targetBuffer[, targetStart][, sourceStart][, sourceEnd])
Parameters
Here is the description of the parameters used:
 targetBuffer - Buffer object where buffer will be copied.
 targetStart - Number, Optional, Default: 0
 sourceStart - Number, Optional, Default: 0
 sourceEnd - Number, Optional, Default: buffer.length


7-----------Slice Buffer
Syntax
Following is the syntax of the method to get a sub-buffer of a node buffer:
buf.slice([start][, end])
Parameters
Here is the description of the parameters used:
 start - Number, Optional, Default: 0
 end - Number, Optional, Default: buffer.length


8-------------Buffer Length
Syntax
Following is the syntax of the method to get a size of a node buffer in bytes:
buf.length;

========================================================================

Streams


What are Streams?
Streams are objects that let you read data from a source or write data to a destination in
continuous fashion.

 In Node.js, there are four types of streams:

 Readable - Stream which is used for read operation.
 Writable - Stream which is used for write operation.
 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:
 data - This event is fired when there is data is available to read.
 end - This event is fired when there is no more data to read.
 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.


1---------------Reading from a Stream

Create a text file named input.txt having the following content:

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!



Create a js file named main.js with the following code:

var fs = require("fs");
var data = '';
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Set the encoding to be utf8.
readerStream.setEncoding('UTF8');
// Handle stream events --> data, end, and error
readerStream.on('data', function(chunk) {
 data += chunk;
});
readerStream.on('end',function(){
 console.log(data);
});
readerStream.on('error', function(err){
 console.log(err.stack);
});
console.log("Program Ended");

Now run the main.js to see the result:

$ node main.js

Verify the Output.
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!





2----------Writing to a Stream

Create a js file named main.js with the following code:
var fs = require("fs");
var data = 'Simply Easy Learning';
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
// Write the data to stream with encoding to be utf8
writerStream.write(data,'UTF8');

// Mark the end of file
writerStream.end();
// Handle stream events --> finish, and error
writerStream.on('finish', function() {
 console.log("Write completed.");
});
writerStream.on('error', function(err){
 console.log(err.stack);
});
console.log("Program Ended");
Now run the main.js to see the result:
$ node main.js
Verify the Output.
Program Ended
Write completed.
Now open output.txt created in your current directory; it should contain the following:
Simply Easy Learning


3----------Piping the Streams
Piping is a mechanism where we provide the output of one stream as the input to another
stream. It is normally used to get data from one stream and to pass the output of that
stream to another stream. There is no limit on piping operations. Now we'll show a piping
example for reading from one file and writing it to another file.

Create a js file named main.js with the following code:

var fs = require("fs");
// Create a readable stream
var readerStream = fs.createReadStream('input.txt');
// Create a writable stream
var writerStream = fs.createWriteStream('output.txt');
Node.js
46
// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);
console.log("Program Ended");
Now run the main.js to see the result:
$ node main.js

Verify the Output.
Program Ended
Open output.txt created in your current directory; it should contain the following:
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!




File System




Node implements File I/O using simple wrappers around standard POSIX funct
ions. The
Node File System (fs) module can be imported using the following syntax:

var fs = require("fs")


Synchronous vs Asynchronous

Every method in the fs module has synchronous as well as asynchronous forms.
Asynchronous methods take the last parameter as the completion function callback and
the first parameter of the callback function as error.
It is better to use an asynchronous
method instead of a synchronous method, as the former never blocks a program during
its execution, whereas the second one does.

Example
Create a text file named input.txt with the following content:

Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Let us create a js file named main.js with the following code:

var fs = require("fs");

// Asynchronous read
fs.readFile('input.txt', function (err, data) {
 if (err) {
 return console.error(err);
 }
 console.log("Asynchronous read: " + data.toString());
});

// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());
console.log("Program Ended");


Now run the main.js to see the result:
$ node main.js

Verify the Output.
Synchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Program Ended
Asynchronous read: Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!


1-----------Open a File
Syntax
Following is the syntax of the method to open a file in asynchronous mode:
fs.open(path, flags[, mode], callback)


2------------Get File Information
Syntax
Following is the syntax of the method to get the information about a file:
fs.stat(path, callback)



3------------Writing a File
Syntax
Following is the syntax of one of the methods to write into a file:
fs.writeFile(filename, data[, options], callback)




4-------------Reading a File
Syntax
Following is the syntax of one of the methods to read from a file:
fs.read(fd, buffer, offset, length, position, callback)



5-------------Closinga File
Syntax
Following is the syntax to close an opened file:
fs.close(fd, callback)




































































No comments:

Post a Comment