Sitemap
Sanduni Jayasinghe

Sanduni Jayasinghe

Software Engineering Undergraduate at SLIIT

NodeJS

8 min readMay 13, 2022

--

Press enter or click to view image in full size

Introduction to Node.js

Ryan Dahl is the developer of Nodejs. It was made with the intention of generating real-time websites with push capabilities (WebSockets). NodeJS is an open-source, cross-platform runtime environment for server-side and networking applications.

Outside of the browser, Node.js operates the V8 JavaScript engine, which is at the core of Google Chrome. As a result, Node.js is extremely fast. Without creating a new thread for each request, Node.js software operates in a single process. NodeJS is lightweight and efficient because it uses an event-driven, non-blocking I/O model. It is ideal for real-time data-intensive applications that operate across multiple devices.

NodeJS includes a number of JavaScript libraries to assist with basic programming. NodeJS eco-system ‘npm’ is the largest in the world for open source libraries.

Event loop

Press enter or click to view image in full size

Node.js is a single-threaded event-driven platform that is capable of running non-blocking, asynchronous programming. Node.js is memory efficient because of these features. Despite the fact that JavaScript is single-threaded, the event loop allows Node.js to conduct non-blocking I/O operations. When and when possible, it is done by delegating activities to the operating system.

Because most operating systems are multi-threaded, they can manage numerous background operations. If one of these actions is finished, the kernel notifies Node.js, and the callback associated with that action is stored in the event queue, where it will be performed later.

Features of Event Loop:

✤ Allows us to use callbacks and promises.

✤ Executes the tasks starting from the oldest first.

✤ An event loop is an infinite loop that waits for tasks, executes them, and then sleeps until new tasks arrive.

✤ When the call stack is empty, i.e. there are no continuing tasks, the event loop processes tasks from the event queue.

Use Cases

➣ For CPU-intensive, massive computational applications, Nodejs is the ideal platform.

➣ Ideal for creating scalable and speedy network applications.

➣ NodeJS can handle a large number of simultaneous connections while maintaining great performance.

➣ Instead of spawning a new thread for each connection, NodeJS handles everything in a single thread using a non-blocking I/O model.

➣ Over 1 million concurrent connections have been established with NodeJS.

➣ Bubbling errors all the way up to the NodeJS core event loop will cause the program to fail.

Press enter or click to view image in full size

● I/O bound applications.

● Data streaming applications.

● Data-intensive real-time applications.

● JSON APIs-based applications.

● Single-page applications.

Advantages

People frequently ask, “Why to use Node.js?”

The Node.js framework for web applications has numerous advantages.

The following are some of the benefits:

● Ability to utilize a single programming language from beginning to completion of an application.

● Scaling NodeJS apps horizontally and vertically is simple.

● Speed & Performance(increased via caching modules into memory after the first use.)

● Easily extensible.

● Support for common tools like unit testing.

● Proxy Server Ability

● Open-Source NPM Repository

Disadvantages

● Not suitable for computationally intensive tasks.

● Not suitable for computationally intensive tasks.

● Despite the fact that there are many libraries accessible, the number of robust libraries is quite low.

Node Package Manager

NPM is a command-line utility for installing, updating, and uninstalling Node.js packages in your application. It also serves as an online repository for Node.js packages. The global node community builds helpful modules that are published as packages in this repository.

All dependencies are installed by default in the ‘node modules’ directory. All information about the NodeJS application is contained in the package.json file. The file should be placed in the application’s root directory. Name, version, author, repository, needed node version, scripts, and dependencies are all included in ‘package.json’.

To denote the compatible version numbers npm has a mechanism for defining them;

● Less than or equal ‘<=’, greater than or equal ‘>=’.

● Approximately equivalent to ‘~’.

● Compatible with ‘^’.

● Any ‘*’.

● Any ‘1.2.x’.

● Latest ‘latest’

There are two types of dependencies ‘devDependencies’ (development time dependencies) and ‘dependencies’ (application runtime dependencies). DevDependencies are modules that are only necessary during development, whereas dependencies are modules that are also required at runtime.

Node require

When loading modules, NodeJS uses the commonJS pattern. Require modules are loaded in a synchronous fashion and are cached after the first use. If the file does not begin with./,../, or / module is not a core module, NodeJS will check the node modules directory for the dependency.

Let’s do some coding…..

Press enter or click to view image in full size

Hello world in Nodejs

Let’s look at the elements of a Node.js application before we make a real “Hello, World!” application. The three main elements of a Node.js application are as follows:

  1. Import required modules: By using require directive we can import required modules in the application.

2. Create server: We need to create a server to listen a client requests similar to Apache or IIS server.

3. Read request and return response :We need to create a server to listen a client requests similar to Apache or IIS server.

Console Based Hello World Example:

Let’s use the Node.js console module to print output on your system console. Create a JavaScript file nodejs_hello_console.js and type below content.

console.log('Hello World');

Execute your script using the node

$ node nodejs_hello_console.js

[output]
Hello World!

Web-Based Hello World Example:

Create a JavaScript file nodejs_hello_web.js and add the following content.

const http = require('http');const host = '0.0.0.0';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!');
});
server.listen(port, host, () => {
console.log('Web server running at http://%s:%s',host,port );
});

Now execute the script using node.

$ node nodejs_hello_web.js

[output]
Web server running at http://0.0.0.0:3000

Read File

The fs.readFile() method is an intrinsic way of reading the file. This approach reads the whole file into the buffer. The require() method is used to load the fs module.

Get Sanduni Jayasinghe’s stories in your inbox

Join Medium for free to get updates from this writer.

Syntax:

fs.readFile( filename, encoding, callback_function )

Example:

// Node.js program to demonstrate
// the fs.readFile() method
// Include fs module
var fs = require('fs');
// Use fs.readFile() method to read the file
fs.readFile('Demo.txt', 'utf8', function(err, data){

// Display the file content
console.log(data);
});
console.log('readFile called');

OutPut:

readFile called
undefined

The output is undefined which means the file is null. It begins reading the file while also running the code. The function will be called when the file has been read; in the meantime, the ‘readFile called’ statement will be displayed, then the contents of the file are printed.

Write File

The fs.writeFile() method is used to write data to a file in an asynchronous manner.

Syntax:

fs.writeFile( file, data, options, callback )

Example:

// Node.js program to demonstrate the
// fs.writeFile() method
// Import the filesystem module
const fs = require('fs');
let data = "This is a file containing a collection of books.";fs.writeFile("books.txt", data, (err) => {
if (err)
console.log(err);
else {
console.log("File written successfully\n");
console.log("The written has the following contents:");
console.log(fs.readFileSync("books.txt", "utf8"));
}
});

OutPut:

File written successfully

The written has the following contents:
This is a file containing a collection of books.

Stream the content of a file.

Streams are objects that allow you to continuously read data from a source and write data to a destination. There are four types of streams in Node.js:

  • Readable − Stream which is used for read operation.
  • Writable − Stream which is used for the write operation.
  • Duplex − Stream which can be used for both read and write operations.
  • Transform − A type of duplex stream where the output is computed based on input.

⦿ Reading from a Stream:

Now create the text file named input.txt having the following content:

Streams are objects that allow you to continuously read data from a source and write data to a destination.

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

ar 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");

Run the main.js to see the Out Put:

$ node main.js

OutPut:

Program Ended
Streams are objects that allow you to continuously read data from a source and write data to a destination.

⦿ 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:

$ node main.js

OutPut:

Program Ended
Write completed.

Now open output.txt created in your current directory; it should contain the following.

Simply Easy Learning

⦿ Piping the Streams

Piping is a mechanism where we provide the output of one stream as the input to another stream.

Now 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');

// Pipe the read and write operations
// read input.txt and write data to output.txt
readerStream.pipe(writerStream);

console.log("Program Ended");

Then run the main.js:

$ node main.js

OutPut:

Program Ended

Open output.txt created in your current directory; it should contain the following:

Streams are objects that allow you to continuously read data from a source and write data to a destination.

⦿ Chaining the Streams

Chaining is a way to connect the output of one stream to another stream and create a chain of multiple stream operations.

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

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.");

Now run the main.js:

$ node main.js

Output:

File Compressed.

Input.txt has been compressed, and a file called input.txt.gz has been produced in the current directory. Let’s try decompressing the same file with the code below.

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.");

Now run the main.js

OutPut:

File Decompressed.

Closing Thoughts

So far we have discussed Nodejs, which is an open-source, cross-platform runtime environment for server-side and networking applications. Also, use cases of Nodejs and advantages. Finally we do some coding examples using Nodejs.

Thank you for taking the time to read; If you enjoyed this article, share it with your friends and colleagues!

--

--

Sanduni Jayasinghe

Written by Sanduni Jayasinghe

Software Engineering Undergraduate at SLIIT