0% found this document useful (0 votes)
6 views13 pages

Chapter 2

Good Knowledge

Uploaded by

Ganesh Hasnale
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)
6 views13 pages

Chapter 2

Good Knowledge

Uploaded by

Ganesh Hasnale
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/ 13

Chapter-2 Node Js Module

2.2 Buffer
2.3 Module
2.4 Module Types
2.5 Core Modules
2.6 Local Modules
2.7 Module.Exports

Node.js Basics

Primitive Types
Node.js includes following primitive types:

● String
● Number
● Boolean
● Undefined
● Null
● RegExp

Everything else is an object in Node.js.

Loose Typing : JavaScript in Node.js supports loose typing like the browser's JavaScript. Use var
keyword to declare a variable of any type.

Object Literal : Object literal syntax is same as browser's JavaScript.

Example: Object

Copy

var obj = {
authorName: 'Ryan Dahl',
language: 'Node.js'
}
Functions
Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript. A function can
have attributes and properties also. It can be treated like a class in JavaScript.
Example: Function

Copy

function Display(x)
{
console.log(x);
}

Display(100);
Buffer
Node.js includes an additional data type called Buffer (not available in browser's JavaScript). Buffer is
mainly used to store binary data, while reading from a file or receiving packets over the network.
process object
Each Node.js script runs in a process. It includes process object to get all the information about the current
process of Node.js application.
The following example shows how to get process information in REPL using process object.
> process.execPath
'C:\\Program Files\\nodejs\\node.exe'
> process.pid
1652
> process.cwd()
'C:\\'

Defaults to local
Node's JavaScript is different from browser's JavaScript when it comes to global scope. In the browser's
JavaScript, variables declared without var keyword become global. In Node.js, everything becomes local by
default.
Access Global Scope
In a browser, global scope is the window object. In Node.js, global object represents the global scope.
To add something in global scope, you need to export it using export or module.export. The same way,
import modules/object using require() function to access it from the global scope.
For example, to export an object in Node.js, use exports.name = object.
Example:

Copy

exports.log =
{
console: function(msg)
{
console.log(msg);
},
file: function(msg)
{
// log to file here
}
}
Now, you can import log object using require() function and use it anywhere in your Node.js project.
Node provides Buffer class which provides instances to store raw data similar to an array of integers but
corresponds to a raw memory allocation outside the V8 heap.
Buffer class is a global class that can be accessed in an application without importing the buffer module.
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".
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.
Return Value
This method returns the number of octets written. If there is not enough space in the buffer to fit the entire
string, it will write a part of the string.
Example
buf = new Buffer(256);
len = buf.write("Simply Easy Learning");

console.log("Octets written : "+ len);


When the above program is executed, it produces the following result −
Octets written : 20
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.
Return Value
This method decodes and returns a string from buffer data encoded using the specified character set
encoding.
Example
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97;
}

console.log( buf.toString('ascii')); // outputs: abcdefghijklmnopqrstuvwxyz


console.log( buf.toString('ascii',0,5)); // outputs: abcde
console.log( buf.toString('utf8',0,5)); // outputs: abcde
console.log( buf.toString(undefined,0,5)); // encoding defaults to 'utf8', outputs abcde
When the above program is executed, it produces the following result −
abcdefghijklmnopqrstuvwxyz
abcde
abcde
abcde
Convert Buffer to JSON

Syntax
Following is the syntax of the method to convert a Node Buffer into JSON object −
buf.toJSON()
Return Value
This method returns a JSON-representation of the Buffer instance.
Example
var buf = new Buffer('Simply Easy Learning');
var json = buf.toJSON(buf);

console.log(json);
When the above program is executed, it produces the following result −
{ type: 'Buffer',
data:
[
83,
105,
109,
112,
108,
121,
32,
69,
97,
115,
121,
32,
76,
101,
97,
114,
110,
105,
110,
103
]
}
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.
Return Value
This method returns a Buffer instance.
Example
var buffer1 = new Buffer('TutorialsPoint ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = Buffer.concat([buffer1,buffer2]);

console.log("buffer3 content: " + buffer3.toString());


When the above program is executed, it produces the following result −
buffer3 content: TutorialsPoint Simply Easy Learning
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
Return Value
Returns a number indicating whether it comes before or after or is the same as the otherBuffer in sort order.
Example
var buffer1 = new Buffer('ABC');
var buffer2 = new Buffer('ABCD');
var result = buffer1.compare(buffer2);
if(result < 0) {
console.log(buffer1 +" comes before " + buffer2);
} else if(result === 0) {
console.log(buffer1 +" is same as " + buffer2);
} else {
console.log(buffer1 +" comes after " + buffer2);
}
When the above program is executed, it produces the following result −
ABC comes before ABCD
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
Return Value
No return value. Copies data from a region of this buffer to a region in the target buffer even if the target
memory region overlaps with the source. If undefined, the targetStart and sourceStart parameters default to
0, while sourceEnd defaults to buffer.length.
Example
var buffer1 = new Buffer('ABC');

//copy a buffer
var buffer2 = new Buffer(3);
buffer1.copy(buffer2);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: ABC
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
Return Value
Returns a new buffer which references the same memory as the old one, but offset and cropped by the start
(defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
Example
var buffer1 = new Buffer('TutorialsPoint');

//slicing a buffer
var buffer2 = buffer1.slice(0,9);
console.log("buffer2 content: " + buffer2.toString());
When the above program is executed, it produces the following result −
buffer2 content: Tutorials
Buffer Length

Syntax
Following is the syntax of the method to get a size of a node buffer in bytes −
buf.length;
Return Value
Returns the size of a buffer in bytes.
Example
var buffer = new Buffer('TutorialsPoint');

//length of the buffer


console.log("buffer length: " + buffer.length);
When the above program is executed, it produces following result −
buffer length: 14
Methods Reference
Following is a reference of Buffers module available in Node.js. For more detail, you can refer to the official
documentation.

Class Methods
Sr.No. Method & Description

1 Buffer.isEncoding(encoding)
Returns true if the encoding is a valid encoding argument, false
otherwise.

2 Buffer.isBuffer(obj)
Tests if obj is a Buffer.
3 Buffer.byteLength(string[, encoding])
Gives the actual byte length of a string. encoding defaults to 'utf8'. It is
not the same as String.prototype.length, since String.prototype.length
returns the number of characters in a string.

4 Buffer.concat(list[, totalLength])
Returns a buffer which is the result of concatenating all the buffers in the
list together.

5 Buffer.compare(buf1, buf2)
The same as buf1.compare(buf2). Useful for sorting an array of buffers.

Node.js Module
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files
which can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global
scope. Also, each module can be placed in a separate .js file under a separate folder.
Node.js implements CommonJS modules standard. CommonJS is a group of volunteers who define
JavaScript standards for web server, desktop, and console application.
Node.js Module Types
Node.js includes three types of modules:

1. Core Modules
2. Local Modules
3. Third Party Modules

Node.js Core Modules


Node.js is a light weight framework. The core modules include bare minimum functionalities of Node.js.
These core modules are compiled into its binary distribution and load automatically when Node.js process
starts. However, you need to import the core module first in order to use it in your application.
The following table lists some of the important core modules in Node.js.

Core Module Description

http http module includes classes, methods and events to create Node.js http server.

url url module includes methods for URL resolution and parsing.

querystring querystring module includes methods to deal with query string.

path path module includes methods to deal with file paths.

fs fs module includes classes, methods, and events to work with file I/O.
Core Module Description

util util module includes utility functions useful for programmers.

Loading Core Modules


In order to use Node.js core or NPM modules, you first need to import it using require() function as shown
below.
var module = require('module_name');
As per above syntax, specify the module name in the require() function. The require() function will return an
object, function, property or any other JavaScript type, depending on what the specified module returns.
The following example demonstrates how to use Node.js http module to create a web server.
Example: Load and Use Core http Module

Copy

var http = require('http');

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

//write code here

});

server.listen(5000);
In the above example, require() function returns an object because http module returns its functionality as an
object, you can then use its properties and methods using dot notation e.g. http.createServer().
Module.Exports

The module.exports is a special object which is included in every JavaScript file in the Node.js application
by default. The module is a variable that represents the current module, and exports is an object that will be
exposed as a module. So, whatever you assign to module.exports will be exposed as a module.
Let's see how to expose different types as a module using module.exports.
Export Literals
As mentioned above, exports is an object. So it exposes whatever you assigned to it as a module. For
example, if you assign a string literal then it will expose that string literal as a module.
The following example exposes simple string message as a module in Message.js.
Message.js

Copy

module.exports = 'Hello world';


Now, import this message module and use it as shown below.
app.js

Copy

var msg = require('./Messages.js');


console.log(msg);
Run the above example and see the result, as shown below.
C:\> node app.js
Hello World

Note:

You must specify ./ as a path of root folder to import a local module. However, you do not need to specify
the path to import Node.js core modules or NPM modules in the require() function.

Export Object
The exports is an object. So, you can attach properties or methods to it. The following example exposes an
object with a string property in Message.js file.
Message.js

Copy

exports.SimpleMessage = 'Hello world';

//or

module.exports.SimpleMessage = 'Hello world';


In the above example, we have attached a property SimpleMessage to the exports object. Now, import and
use this module, as shown below.
app.js

Copy

var msg = require('./Messages.js');

console.log(msg.SimpleMessage);
In the above example, the require() function will return an object { SimpleMessage : 'Hello World'} and
assign it to the msg variable. So, now you can use msg.SimpleMessage.
Run the above example by writing node app.js in the command prompt and see the output as shown below.
C:\> node app.js
Hello World

In the same way as above, you can expose an object with function. The following example exposes an object
with the log function as a module.
Log.js

Copy

module.exports.log = function (msg) {


console.log(msg);
};
The above module will expose an object- { log : function(msg){ console.log(msg); } } . Use the above
module as shown below.
app.js

Copy
var msg = require('./Log.js');

msg.log('Hello World');
Run and see the output in command prompt as shown below.
C:\> node app.js
Hello World

You can also attach an object to module.exports, as shown below.


data.js

Copy

module.exports = {
firstName: 'James',
lastName: 'Bond'
}
app.js

Copy

var person = require('./data.js');


console.log(person.firstName + ' ' + person.lastName);
Run the above example and see the result, as shown below.
C:\> node app.js
James Bond

Export Function
You can attach an anonymous function to exports object as shown below.
Log.js

Copy

module.exports = function (msg) {


console.log(msg);
};
Now, you can use the above module, as shown below.
app.js

Copy

var msg = require('./Log.js');

msg('Hello World');
The msg variable becomes a function expression in the above example. So, you can invoke the function
using parenthesis (). Run the above example and see the output as shown below.
C:\> node app.js
Hello World

Export Function as a Class


In JavaScript, a function can be treated like a class. The following example exposes a function that can be
used like a class.
Person.js

Copy

module.exports = function (firstName, lastName) {


this.firstName = firstName;
this.lastName = lastName;
this.fullName = function () {
return this.firstName + ' ' + this.lastName;
}
}
The above module can be used, as shown below.
app.js

Copy

var person = require('./Person.js');

var person1 = new person('James', 'Bond');

console.log(person1.fullName());
As you can see, we have created a person object using the new keyword. Run the above example, as shown
below.
C:\> node app.js
James Bond

In this way, you can export and import a local module created in a separate file under root folder.
Node.js also allows you to create modules in sub folders. Let's see how to load module from sub folders.
Load Module from the Separate Folder
Use the full path of a module file where you have exported it using module.exports. For example, if the log
module in the log.js is stored under the utility folder under the root folder of your application, then import it,
as shown below.
app.js

Copy

var log = require('./utility/log.js');


In the above example, . is for the root folder, and then specify the exact path of your module file. Node.js
also allows us to specify the path to the folder without specifying the file name. For example, you can
specify only the utility folder without specifying log.js, as shown below.
app.js

Copy

var log = require('./utility');


In the above example, Node.js will search for a package definition file called package.json inside the utility
folder. This is because Node assumes that this folder is a package and will try to look for a package
definition. The package.json file should be in a module directory. The package.json under utility folder
specifies the file name using the main key, as shown below.
./utility/package.json
Copy

{
"name" : "log",
"main" : "./log.js"
}
Now, Node.js will find the log.js file using the main entry in package.json and import it.

You might also like