Chapter 2
Chapter 2
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
Loose Typing : JavaScript in Node.js supports loose typing like the browser's JavaScript. Use var
keyword to declare a variable of any type.
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");
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;
}
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]);
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');
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
http http module includes classes, methods and events to create Node.js http server.
url url module includes methods for URL resolution and parsing.
fs fs module includes classes, methods, and events to work with file I/O.
Core Module Description
Copy
});
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
Copy
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
//or
Copy
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
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
Copy
module.exports = {
firstName: 'James',
lastName: 'Bond'
}
app.js
Copy
Export Function
You can attach an anonymous function to exports object as shown below.
Log.js
Copy
Copy
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
Copy
Copy
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
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.