Node.js development environment can be setup in Windows, Mac, Linux and Solaris. The following tools are required for developing a Node.js application on any platform.
1. Node.js
2. Node Package Manager (NPM)
3. IDE (Integrated Development Environment) or TextEditor
NPM (Node Package Manager) is included in Node.js installation since Node version 0.6.0., so there is no need to install it separately.
Visit Node js official website is https://nodejs.org/en/
It will automatically detect OS and display download link as per your Operating System. For example, it will display following download link for 64 bit Windows OS.
Download Node.JS Installer for Windows
Download node MSI for windows by clicking on 18.15.0 LTS or 19.8.1 Current button.
After you download the MSI, double-click on it to start the installation as shown below.
Click Next to read and accept the License Agreement and then click Install. It will install Node.js quickly on your computer. Finally, click finish to complete the installation.
Once you install Node.js on your computer, you can verify it by opening the command prompt and typing node -v. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine, as shown below.
Visit Node.js official web site https://nodejs.org/en/download page. Click on the appropriate installer for Mac (.pkg or .tar.gz) or Linux to download the Node.js installer.
Node
Once downloaded, click on the installer to start the Node.js installation wizard. Click on Continue and follow the steps. After successful installation, it will display summary of installation about the location where it installed Node.js and NPM.
After installation, verify the Node.js installation using terminal window and enter the following command. It will display the version number of Node.js installed on your Mac.
$ node -v
Optionally, for Mac or Linux users, you can directly install Node.js from the command line using Homebrew package manager for Mac OS or Linuxbrew package manager for Linux Operating System. For Linux, you will need to install additional dependencies, viz. Ruby version 1.8.6 or higher and GCC version 4.2 or higher before installing node.
$ brew install node
Node.js application uses JavaScript to develop an application. So, you can use any IDE or texteditor tool that supports JavaScript syntax. However, an IDE that supports auto complete features for Node.js API is recommended e.g. Visual Studio code, Visual Studio, Sublime text, Eclipse, Aptana etc.
Here, showing Visual Studio code installation
Step 1 – Visit the official website of the Visual Studio Code using any web browser like Google Chrome, Microsoft Edge, etc.
https://code.visualstudio.com/Download
Step 2 – Click on Download for windows
Step 3: Click on the installer icon to start the installation process of the Visual Studio Code.
Step 4: After the Installer opens, it will ask you for accepting the terms and conditions of the Visual Studio Code. Click on I accept the agreement and then click the Next button.
Step 5: Choose the location data for running the Visual Studio Code. It will then ask you for browsing the location. Then click on Next button.
Step 6: Then it will ask for beginning the installing setup. Click on the Install button.
Step 7: After clicking on Install, it will take about 1 minute to install the Visual Studio Code on your device.
Step 8: After the Installation setup for Visual Studio Code is finished, it will show a window like this below. Tick the “Launch Visual Studio Code” checkbox and then click Next.
Step 9: After the previous step, the Visual Studio Code window opens successfully. Now you can create a new file in the Visual Studio Code window and choose a language of yours to begin your programming journey!
So this is the way of installing Visual Studio Code on Windows system.
Understanding REPL (Read Eval Print Loop) / node JS console. Or node shell.
Description: REPL stands for Read Eval Print Loop. It is a quick and easy way to test simple Node.js/Javascript code. The Node.JS Read Eval Print Loop (REPL) is an interactive shell that process Node.js expressions. The shell reads Javascript code the user enter, evaluates the result of interpreting the line of code, prints the result of the user, and loops until the user signals to quit.
The following table lists important REPL commands.
To work the REPL (Node shell), follow the steps which are given below.
Step 1 - open command prompt (in Windows) or terminal (in Mac or UNIX/Linux)
Step 2 - Type node as shown below. It will change the prompt to > in Windows and MAC.
Examples in REPL
Ex. 1 Console
>console.log(“Hello World”);
>console.log(“Welcome to the node js session”);
Output:
Ex.2 Function
>function addition(x,y)
…{
…return x+y;
…}
>addition(12,50);
>function square(x)
…{
…return x*x
…}
>square(5);
>function area(x)
…{
…return 3.14*x*x
…}
>area(4);
>function cube(x)
…{
…return x*x*x
…}
>cube(3);
Output:
Ex.3 Variable
>10
>20
>x=10
>y=20
>x+y
>var x=10
>var y=70
>x+y
Output:
Ex.4 Javascript function
>function myfunction(n1,n2)
…{
…console.log(n1+n2)
…}
>myfunction(8,5);
>function mysub(n1,n2)
…{
…console.log(n1-n2)
…}
>mysub(20,10);
>function mydiv(n1,n2)
…{
…console.log(n1/n2)
…}
>mydiv(35,5);
>function mymulti(n1,n2)
…{
…console.log(n1*n2)
…}
>mymulti(5,4);
Output:
Node.js modules are useful to move the common functionalities to separate .js file to reuse it in applications based on our requirements.
Each module has its own context, so if we create any new module that won’t interfere with other modules in application.
Type of Modules in Node Js
1. Core (Built-in) Modules
2. Local (Custom) Modules
3. Third Party (External) Modules
List of some core modules in node. Js
Ex 1 os module
Syntax
The syntax for including the OS module in your application:
var os = require(‘os’);
Code
var os = require (‘os’);
console.log(os.EOL);
console.log(os.arch());
console.log(os.hostname());
console.log(os.totalmem());
console.log(os.freemem());
console.log(os.platform());
console.log(os.type());
console.log(os.userInfo());
output
PS C:\WebTechnologies\practical\OsModule> node osmodule.js
x64
DESKTOP-5LMD8KE
4209967104
1002143744
win32
Windows_NT
{
uid: -1,
gid: -1,
username: ‘Admin’,
homedir: ‘C:\\Users\\Admin’,
shell: null
}
Ex 2 path module
Code
// understanding path module in node js
var path = require (‘path’);
console.log(path.dirname(‘C:/avantika/practical/OsModule/demo.js’));//return directory name
console.log(path.basename(‘C:/avantika/practical/OsModule/demo.js’));//return file name
console.log(path.extname(‘C:/avantika/practical/OsModule/demo.js’));//return extension name
console.log(path.parse(‘C:/avantika/practical/OsModule/demo.js’))
const mypath = (path.parse(‘C:/avantika/practical/OsModule/demo.js’));
console.log(mypath.name);
console.log(mypath.root);
console.log(mypath.ext);
Output
PS C:\avantika\practical\OsModule> node demo.js
C:/avantika/practical/OsModule
demo.js
.js
{
root: ‘C:/’,
dir: ‘C:/avantika/practical/OsModule’,
base: ‘demo.js’,
ext: ‘.js’,
name: ‘demo’
}
demo
C:/
.js
PS C:\avantika\practical\OsModule>
Ex 3 url module
Code
//understanding url module in node js
var url = require (‘url’);
var adr = ‘https://www.google.com/search?client=firefox-b-d&q=url+module+in+node+js’;
var q= url.parse(adr, true);
console.log(q.host); //return www.google.com
console.log(q.pathname); //return /search
console.log(q.search); // return?client=firefox-b-d&q=url+module+in+node+js’
output
PS C:\avantika\practical\OsModule> node demo.js
/search
?client=firefox-b-d&q=url+module+in+node+js
PS C:\avantika\practical\OsModule>
exports.add=function(x,y) {
return x+y;
};
exports.sub=function(x,y) {
return x-y;
};
exports.div=function(x,y) {
return x/y;
};
var calculator= require (‘./calc.js’);
var x= 50;
var y = 5;
console.log(“additon of x and y is “,calculator.add(x,y));
console.log(“subtraction of x and y is “,calculator.sub(x,y));
console.log(“multiplication of x and y is “,calculator.mul(x,y));
console.log(“division of x and y is “,calculator.div(x,y));
NPM is the Package Manager for Node.js packages/modules
NPM is installed by default when you install Node.js
Benefits of NPM:
1. It Provides and hosts Online repositories for node.js packages/modules which can be easily downloaded and used in our projects. You can find them here: npmjs.com
2. It Provides the Command-line utility in order to install various Node.js packages, manage Node.js versions and dependencies of the packages.
Check NPM Version
npm -v
Install Packages via NPM
1. Installed packages goes inside node_modules folder.
2. In Short you can use - npm i <package_name>
3. You can check out npm packages - npmjs.com
4. In Latest version, --save is optional. it automatically save the package as a dependency in package.json
Syntax:
npm install <package_name>
Install the package globally
npm install <package_name> -g
Save the package as dependency
npm install <package_name> --save
Save the package as dev-dependency
npm install <package_name> --save-dev
Install the latest version of a package
npm install <package_name>@latest
Install any particluar version of a package
npm install <package_name>@<version_number>
//npm install express@4.11.1
Uninstalling Packages/Modules via NPM
npm uninstall <package_name>
Update Packages/Modules via NPM
npm update <package_name>
//aliases: up, upgrade
List all Installed Packages
npm ls
package.json
{
“name”: “MyNodeProject”,
“version”: “1.0.0”,
“description”: “My Nodejs Project”,
“main”: “app.js”,
“author”: {
“name”: “Dev”,
“email”: “dev@xyz.com”
},
“dependencies”: {
“body-parser”: “~1.10.2”,
“express”: “~4.11.1”,
“nodemon”: “^1.14.12”
},
“devDependencies”: {
“grunt”: “^0.4.5”,
“grunt-contrib-jshint”: “^0.10.0”,
“jshint-stylish”: “^0.2.0”,
“time-grunt”: “^0.3.2”
}
}
NVM stands for Node Version Manager, You can use nvm to change your node.js versions very easily this is very helpful if you are working on multiple projects of Node.js having different versions, etc.
Benefits of NVM:
1. Easy to downloaded and use in your projects. You can find them here: NVM Github Link
2. It Provides the Command-line utility in order to manage different Node.js versions on the same system/machine.
Install NPM:
Use the following command to install NVM on your machine
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash
OR
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash
Some useful commands of NVM:
Check NVM Version
nvm --version
Check all Node.js versions installed on your machine
nvm ls
Check Node.js versions available to downloaded
nvm ls--remote
Install a particular version of Node.js
nvm install NODE_VERSION_NAME
//Replace NODE_VERSION_NAME to actual node.js version
Use a particular version of Node.js
nvm use NODE_VERSION_NAME
//Replace NODE_VERSION_NAME to actual node.js version
Set default version of Node.js
nvm alias default NODE_VERSION_NAME
//Replace NODE_VERSION_NAME to actual node.js version
Create new alias of Node.js
nvm alias ALIAS_NAME NODE_VERSION_NAME
//Replace
//NODE_VERSION_NAME to actual node.js version
//ALIAS_NAME to actual alias name
App.js
const express= require (‘express’);
const app= express();// initializing my express module
app.get(‘/’, function (req,res){
res.send(‘hello everyone for offline lectures’);
})
app.listen(3000, function(req,res){
console.log(“server is running on console”);
});
A function in NodeJS is either synchronous or asynchronous.
An asynchronous function is a function which has the functionality to call events when they complete the execution. The asynchronous function does not wait for any task to complete, it continues its execution with next instruction.
Callback function is a function which is called automatically after the completion of the execution of a time-intensive process.
We can understand it by one example - reading a text file using NodeJS.
Here, we assume that the text file is big so the process of reading this file is time-consuming. So, if we are to take a normal synchronous function for reading this text file, how it works is shown in the below example.
1) Create one text file name – myfile.txt
2) Create one js file to read the contents of file
3) Run the file
Practical 4(a)
Myfile.txt
this is my file
which will have huge amount of data
and it will take time to read.
Sync.js
var fs = require(‘fs’);
console.log(‘here we started’);
console.log(‘--------------------------------’);
var contents = fs.readFileSync(‘myfile.txt’);
console.log(contents.toString());
console.log(‘--------------------------------’);
console.log(‘here we done’);
node sync.js
Practical 4(b)
reading file with asynchronous way
async.js
var fs= require(‘fs’);
console.log(‘here we started.....’);
var contents= fs.readFile(‘myfile.txt’,function(err, data){
if(err) throw err;
console.log(data.toString());
});
console.log(‘here we done .....................’);
node async.js
emit(event, [arg1], [arg2], [arg3],….[]): emit() is used to raise an event. The first argument event is the name of the event.
on(event, listener): on() listens to the event and executes the event handler. The listener is the event handler.
once(event, listener): once() adds a one time listener.
addListener(event, listener): addListener() adds a listener to the end of listeners array for the specified event.
removeListener(event, listener): removeListener() removes a listener from the listener’s array for the specified event.
removeAllListeners([event]): removeAllListeners() removes all the listeners of the specified events.
listeners(event): listeners() returns an array of the specified event.
setMaxListeners(n): If more than 10 listeners are added to the event, the EventEmitter class gives a warning by default. This function allows the number of listeners to increase, in order.
The following table lists all the important methods of EventEmitter class.
Events in NodeJS are same as a callback. A callback function is called when a function execution is completed where the events have to be fired based on the observer.
Every event has listeners and when an event is fired its related listener function starts the execution.
Below is some syntax for generating and firing events.
1. For creating a new event var event=require(‘events’); var eventEmitter=new event.EventEmitter();
2. For assigning any function to events. So, when this event is fired, the function gets executed. eventEmitter.on(‘eventName’,functionName);
3. For firing the events. eventEmitter.emit(‘eventName’);
Practical 4(c) on the above information
var events= require(‘events’);
var emitter = new events.EventEmitter();
// listening to event
emitter.on(‘eventname’, () => {
console.log(‘event get fired’);
});
//event fired
emitter.emit(‘eventname’);
OR
const EventEmitter = require(‘events’);
var events= require(‘events’);
var emitter = new EventEmitter();
// listening to event
emitter.on(‘eventname’, () => {
console.log(‘event get fired’);
});
//event fired
emitter.emit(‘eventname’);
----------------------
Practical 4(d) emit with arguments
const EventEmitter = require(‘events’);
const events = require(‘events’);
const emitter = new EventEmitter();
emitter.on(‘saved’, (arg) => {
console.log(`A saved event occurred: number1: ${arg.n1}, number2: ${arg.n2}`);
});
emitter.emit(‘saved’, {
n1:‘10’,
n2: ‘20’
});
Practical 4(e)Myevent.js
//step 1- creating new event
var event= require(‘events’);
var myeventemitter= new event.EventEmitter();
//step 2 creating one function, this function get executed when event is fired.
//myeventemitter.on(‘eventName’,functionName);
myeventemitter.on(‘addition’, function(n1,n2) {
console.log(‘sum of two numbers’,n1+n2);
});
myeventemitter.on(‘multiplication’, function(n1,n2){
console.log(‘multiplication of two numbers’,n1*n2);
});
// step 3 For firing the events.
//myeventemitter.emit(‘eventName’);
myeventemitter.emit(‘addition’, 10,20);
myeventemitter.emit(‘multiplication’,8,9);
console.log(“done!!!!!!!”);
-------------------------------------------------------------------------------------------------------------
Practical 4(f) anotherway.js
// import events module
var events =require (‘events’);
// creating an event emitter object
var myeventemitter = new events.EventEmitter();
// write a function for event1
function listener1(){
console.log(‘event received by listener 1’);
}
// write a function for event2
function listener2(){
console.log(‘event received by listener 2’);
}
// adding listener throgh addListener or on
myeventemitter.addListener(‘write’,listener1);
myeventemitter.on(‘write’, listener2);
//emitting event
myeventemitter.emit(‘write’);
moreevent.js
var events = require(‘events’);
var eventEmitter = new events.EventEmitter();
// listener #1
var listner1 = function listner1() {
console.log(‘listner1 executed.’);
}
// listener #2
var listner2 = function listner2() {
console.log(‘listner2 executed.’);
}
// Bind the connection event with the listner1 function
eventEmitter.addListener(‘connection’, listner1);
// Bind the connection event with the listner2 function
eventEmitter.on(‘connection’, listner2);
var eventListeners = require(‘events’).EventEmitter.listenerCount
(eventEmitter,‘connection’);
console.log(eventListeners + “ Listner(s) listening to connection event”);
// Fire the connection event
eventEmitter.emit(‘connection’);
// Remove the binding of listner1 function
eventEmitter.removeListener(‘connection’, listner1);
console.log(“Listner1 will not listen now.”);
// Fire the connection event
eventEmitter.emit(‘connection’);
eventListeners = require(‘events’).EventEmitter.listenerCount(eventEmitter,’connection’);
console.log(eventListeners + “ Listner(s) listening to connection event”);
console.log(“Program Ended.”);
A function is a parametric block of code defined once and called multiple times later. A function is a set of statements that is invoked in an application to perform a certain action or yield a desired result based on the login in the code. It is a open source javascript runtime environment.
Code:
//simple addition function in node js var add=function(a,b){
return a+b;
}
console.log(‘Addition: ‘+add(10,20));
Output:
Code:
//simple addition function in node js with arrow function var add=(a,b)=> a+b;
console.log(‘Addition: ‘+add(10,20));
Output:
Code:
let myname={firstname: ‘rohit’, lastname: ‘lathigra’
};
(function(){
console.log(myname.firstname, myname.lastname);
})(myname);
Output:
Code:
//anonymous function let show=function(){
console.log(‘show is anonymous function’)
};
show();
Output:
Code:
//using anonymous function as a argument of another function setTimeout(function(){
console.log(‘it gets execute after 1 second’)
},1000);
Output:
File system in Node.js is used to read and write file by using the built-in fs module. It is also used to read or write files from console as well as to create new file in specific location and perform read and write operations on it.
Practical 6(a)
1) File handling with read operations
Step 1-
Create myfile.txt and type following lines
This is the file that node js readstream will read the contents
thank you for this!!!!!!!!!!!!!!!!!!!!!!!!111
step 2 –
create file readstream.js and type following code
var fs = require (‘fs’);
var data=‘‘;
var readerStream =fs.createReadStream(‘myfile.txt’);
//encoding with utf8
readerStream.setEncoding(‘utf8’);
readerStream.on(“data”,function(chunk){
data+=chunk;
})
readerStream.on(“end”,function(){
console.log(data);
});
Step 3
Output
Practical 6(b) write file
1) Create file output.txt (without contents)
2) Create file writestream.js and write following code
Writestream.js
var fs= require(‘fs’);
var data=(“this is my data and this will help you to understand the stream concept in node js”);
var writerStream= fs.createWriteStream(‘output.txt’);
writerStream.write(data,‘utf8’);
writerStream.end();
writerStream.on(‘finish’, function(){
});
3) Open output.txt
4) Done
Practical 6(c) utf8
1) Create demo.docs with following code
hello everyone
this file we will use for readwrite utf8 stream in node js
2) Create readwriteutf8.js
var fs = require(‘fs’);
var readerStream = fs.createReadStream(‘demo.docs’);//create redable stream
var writerStream = fs.createWriteStream(‘myoutput.docs’);
readerStream.pipe(writerStream);
3) Open myoutput.docs
Node js has a built-in module called HTTP, which allows node js to transfer data over the Hyper Text Transfer Protocol. Using this module one can create REST API with Node js. It is basically used to communicate with client as well as the user.
Code:
const http=require(‘http’);//including http module http.createServer((req,res) =>{
res.write(“Hello everyone”); res.end();
}).listen(5000);
console.log(‘Server is running properly on port 5000’);
Output:
Code:
const http=require(‘http’);
const server=http.createServer(function(req,res){if(req.url==‘/’) {
res.writeHead(200,{‘Content-Type’: ‘text/html’}); res.write(‘<html><body><h1>This is home page.</h1></body></html>’); res.end();
}else if (req.url==“/contact”){res.writeHead(200,{‘Content-Type’: ‘text/html’});
res.write(‘<html><body><p>This is contact page</p></body></html>’); res.end();
}else if (req.url==“/admin”){res.writeHead(200,{‘Content-Type’: ‘text/html’});
res.write(‘<html><body><p>This is admin page</p></body></html>’); res.end();
} else {
res.end(‘Invalid request’);
}
});
server.listen(5000);
console.log(‘server running on port 5000’);
Output:
Code:
var http=require(‘http’); var fs=require(‘fs’);
fs.readFile(‘./index.html’, function(err, html){if(err)
{
throw err;
}
http.createServer(function(request,response){response.writeHead(200)
response.writeHead(200,{‘content-type’: ‘text/html’}); response.write(html);
response.end();
}).listen(5000);
console.log(‘Server is running properly’);
});
Output:
A stream is a way of data-handling that helps us to obtain a sequential output by reading or writing the input (files, network communications, and any kind of end-to-end information exchange).
That is, they let you read data from a source or write it to a destination or perform any other specific task in an uninterrupted and constant manner.
The stream is not a unique concept to Node.js and it is a part of Unix for quite a long time.
A pipe operator is used to make the programs react with each other by passing streams. Hence, the Node.js stream is used as a basis for all streaming APIs.
Example: When you are streaming YouTube, Netflix, Spotify then, instead of the whole content downloading all at once, it downloads in small chunks while you keep browsing.
Another example can be chatting on Facebook or WhatsApp where the data is continuously flowing between two people.
This is because instead of reading all the data at once in the memory the stream processes it into smaller pieces to make large files easily readable. It is useful because some files are larger than the available free space that you have on your device. Hence, the stream makes such files readable.
Advantages of Stream:
1. Memory efficiency: Stream is memory (spatial) efficient because they enable you to download files in smaller chunks instead of a whole in the memory before you can process it thus, saving space.
2. Time efficiency: Stream is time-efficient because you start processing the data in smaller chunks so the procedure starts earlier compared to the general way, where you have to download the whole data to be able to process it. Hence, this early processing saves a lot of time.
3. Composable data: Data is composed because of the piping ability of the streams which lets them connect together in spite of however heavy the codes. It means that the process of one input getting piped to output keeps on happening.
Types of Stream:
1. Readable stream: It is the stream from where you can receive and read the data in an ordered fashion. However, you are not allowed to send anything. For example fs.createReadStream() lets us read the contents of a file.
2. Writable stream: It is the stream where you can send data in an ordered fashion but you are not allowed to receive it back. For example fs.createWriteStream() lets us write data to a file.
3. Duplex stream: It is the stream that is both readable and writable. Thus you can send in and receive data together. For example net.Socket is a TCP socket.
4. Transform stream: It is the stream that is used to modify the data or transform it as it is read. The transform stream is basically duplex in nature. For example, zlib.createGzip stream is used to compress the data using gzip.
Different operations in a stream are:
1. Reading from a stream: Create a file named input.txt with the following text: This is a code to learn about the reading from a stream.
Filename: main.js
edit close
play_arrow
link
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”);
// Handling data stream event
readerStream.on(“data”, function(chunk) {
data += chunk;
});
// Handling end stream event
readerStream.on(“end”,function() {
console.log(data);
});
// Handling error stream event
readerStream.on(“error”, function(err) {
console.log(err.stack);
});
chevron_right
filter_none
Run main.js file with the following command:
$ node main.js
The output of the above command is shown below:
This is a code to learn about the reading from a stream.
2. Writing to a stream
Filename: main.js
var fs = require(‘fs’);
var data = ‘This is a code to learn“
+ “ about writing in a stream.‘;
// 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();
// Handling finish stream event
writerStream.on(‘finish’, function () {
});
// Handling error stream event
writerStream.on(‘error’, function (err) {
console.log(err.stack);
});
chevron_right
filter_none
Run main.js file with the following command:
$ node main.js
After executing above command, a file named output.txt will be created in the current directory with the following text:
This is a code to learn about writing in a stream.
3. Piping the stream: Piping is an operation or a mechanism where we provide the output of one stream (readable, i.e., the source file) of data as the input to another stream (write-able, i.e. the destination file). It is normally used to get data from one stream (i.e. read from source) and pass the output of that stream to another stream (i.e. write to destination) without managing the flow yourself. It is the easiest way to consume streams. There is no limit on piping operations. It is used to process streamed data in multiple ways. For example, reading from one file and writing it to another.
Create a file named input.txt with the following text:
This is a code to learn about piping the stream.
Filename: main.js
var fs = require(‘fs’);
// Create a readable stream
var readerStream = fs.createReadStream(‘input.txt’);
// Create a writable stream
var writerStream = fs.createWriteStream(‘output.txt’);
// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);
chevron_right
filter_none
Run main.js file with the following command:
$ node main.js
After executing above command, a file named output.txt will be created in current directory with the following text:
This is a code to learn about piping the stream.
4. Chaining the stream: Chaining of the stream is a mechanism of creating a chain of multiple stream operations by connecting the output of one stream with another stream. It is normally used with piping operations. For example, we will use piping and chaining to first compress a file and then decompress the same.
Filename: main.js
var fs = require(‘fs’);
var zlib = require(‘zlib’);
// Compress the file input.txt to input.txt.gz
fs.createReadStream(‘input.txt’)
.pipe(zlib.createGzip())
.pipe(fs.createWriteStream(‘input.txt.gz’));
console.log(‘File Compressed.’);
chevron_right
filter_none
Run main.js file with the following command:
$ node main.js
Output of above command is shown below:
File Compressed.
You will find that input.txt has been compressed and it created a file input.txt.gz in the current directory.
Now code to decompress the above created file is shown below: Filename: main.js
var fs = require(‘fs’);
var zlib = require(‘zlib’);
// Decompress the file input.txt.gz to input.txt
fs.createReadStream(‘input.txt.gz’)
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream(‘input.txt’));
console.log(‘File Decompressed.’);
chevron_right
filter_none
Run main.js file with the following command:
$ node main.js
Output of above command is shown below:
File Decompressed.
You will find that input.txt.gz has been decompressed.