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)




































































Steps to Execute a Node.js Console Application.


Steps to Execute a Node.js Console Application.


  • 1.      download nodejs to your system.
  • 2.      open a notepad write js command "console.log('Hello World');"
  • 3.      save the file as hello.js preferably same location as nodejs.
  • 4.      open command prompt navigate to the location where the nodejs is located. ...
  • 5.      and run the command from the location like c:\program files\nodejs>nodehello.js.




1.      Download the Windows executable here: http://nodejs.org/#download
2.      Copy the file to C:\
3.      Create C:\hello.js
4.      Paste in the following content:
    var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    }).listen(1337, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:1337/');
1.      Save the file
2.      Start -> Run... -> cmd
3.      c:
4.      C:>node hello.js
Server running at http://127.0.0.1:1337/

That's it. This was done on Windows XP.

Monday, August 13, 2018

JavaScript program to Create and Access the Elements of an Array.


JavaScript program to Create and Access the

 Elements of an Array.


The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.

<html>
 <head>
<title>Basic Javascript Array Example</title>

<script language="javascript">
// Empty array
var empty = [];

// Array containing initial elements.
var fruits = ['apple', 'orange', 'kiwi'];

alert(fruits[1]);
</script>
</head>

<body>

</body>

</html>
 

To add elements to an array in javascript, just define a new element at the end of the array. 

You can also use push() to 'push' a new element onto the end of the array, or unshift() to add elements to the start of an array: 


Create an Array
var fruits = ['Apple', 'Banana'];
 
console.log(fruits.length);
// 2
Access (index into) an Array item
var first = fruits[0];
// Apple
 
var last = fruits[fruits.length - 1];
// Banana
Loop over an Array
fruits.forEach(function(item, index, array) {
  console.log(item, index);
});
// Apple 0
// Banana 1
Add to the end of an Array
var newLength = fruits.push('Orange');
// ["Apple", "Banana", "Orange"]
Remove from the end of an Array
var last = fruits.pop(); // remove Orange (from the end)
// ["Apple", "Banana"];
Remove from the front of an Array
var first = fruits.shift(); // remove Apple from the front
// ["Banana"];
Add to the front of an Array
var newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"];
Find the index of an item in the Array
fruits.push('Mango');
// ["Strawberry", "Banana", "Mango"]
 
var pos = fruits.indexOf('Banana');
// 1
Remove an item by index position
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
                                        
// ["Strawberry", "Mango"]
Remove items from an index position
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
console.log(vegetables); 
// ["Cabbage", "Turnip", "Radish", "Carrot"]
 
var pos = 1, n = 2;
 
var removedItems = vegetables.splice(pos, n); 
// this is how to remove items, n defines the number of items to be removed,
// from that position(pos) onward to the end of array.
 
console.log(vegetables); 
// ["Cabbage", "Carrot"] (the original array is changed)
 
console.log(removedItems); 
// ["Turnip", "Radish"]
Copy an Array
var shallowCopy = fruits.slice(); // this is how to make a copy
// ["Strawberry", "Mango"]

Link to sectionSyntax

[element0, element1, ..., elementN]
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)