Node.js: Exploring Modules and File System

ยท

6 min read

Node.js: Exploring Modules and File System
Play this article

Introduction

JavaScript is executed within browsers due to the presence of the V8 engine (Built by Google, written in C++), exclusively designed for browsers. This confinement of JavaScript to browsers is because the v8 engine converts JS code to machine code and computers understand machine code rather than JavaScript, a runtime environment is necessary, to run JS outside the browser.

Node.js wraps up the V8 engine, and it helps the conversion of JavaScript into machine code. Therefore, Node.js is a runtime environment to execute JavaScript on the server side. It's like a special space for server tasks, with extra tools that make those tasks easier. These tools are not found when using JavaScript in a regular web browser.

๐Ÿค“
FOR NERDS: In browsers, the global object is "window," whereas in Node.js, it's not "window" but a distinct global object. This difference means you can't use DOM methods as you would in a browser.

Working of Web

IP ADDRESS :

Each computer connected to the internet has a unique address called IP address, We can connect to the server hosting websites, by entering the IP address of the server in our browser. The Domain name masks up the IP address.

When a client enters a URL in the browser, it will find the IP associated with the domain name and find the server with the address, The browser makes a request, to which the server looks upon and sends a response, which can be either HTML or JSON or XML etc.

HTTP & HTTPS :

The communication between server & client i.e. Request and Response transmission is performed through some protocol called HTTP & HTTPS. (Set of rules for communication between and client)

  • HTTP- Hyper Text Transfer Protocol, defines how the request should look and how data should be transferred.

  • HTTPS- Hyper Text Transfer Protocol Secure, is the same as HTTP with SSL encryption, where all the data that is transmitted is encrypted, making the connection secure.

LOCAL HOST: It is a special type of domain that refers to a server that's running on our machine. It helps us try out and create web applications privately. It's perfect for testing and making sure everything works perfectly before letting others visit our website.

PORT NUMBER: They represent a specific channel or gateway through which servers communicate. They are like specific doors for information on a computer. They make sure data gets to the right program or service, kind of like labels on mailboxes to ensure messages reach the correct place.

Example- http://localhost:3000, 3000 represents the port number


Modules

Node.js is built around the concept of modules, modules are like sets of code to be inserted in an application.

To include a module we use the require() function, and the name of the module is passed as an argument in the case of built-in modules. (In the case of custom modules we specify the directory of the module)

const testModule= require('module-name');

All node.js files are treated as modules, when we require a file, the node automatically looks for the file and runs the file. The require() method returns an object of attributes (variable/function/object) exported by the module using module.export.

Let's create and use a module-

//math.js
function add(a,b){
return a+b;
}
module.export={add};
//app.js
const moduleAdd=require('./math');
console.log(moduleAdd); // Output: { add: [Function: add] }
const ans=moduleAdd.add(2,3); //Using the add function from the imported module
console.log(ans); //Ouput:5

Core Node Modules

Node comes with built-in modules called core node modules, they are pre-installed with the node runtime.

  1. os (Operating System)- const os=require('os'); this module returns the information related to the current operating system.

  2. fs (File System)- const fs=require('fs'); this module returns methods for interacting with the file system, such as reading, writing, updating, deleting files etc.

  3. http and https - These modules enable creation of HTTP and HTTPS servers and make HTTP requests.


File System Module

The File System Module gives us the power to do more with files. We can read them to get information, write new data into them, and if needed remove them completely.

Reading Files

To read files synchronously, we use readFileSync() method, It requires specifying the file's location along with 'utf-8' as parameters. In return, it provides us with the data contained within the file.

๐Ÿ’ก
Note- 'utf-8' is used as the encoding to ensure that the data is read as a human-readable string.

Likewise, we use readFile() method to read files asynchronously, the directory of the file, 'utf-8' and a callback function is passed as an argument, This callback function is activated every time the file is read, and it contains two parameters: the first one for errors and the second one for data.

(Suppose input.txt is in a file called txt in the current directory)

const fs = require('fs');

// Sync- Blocking Code
const textSync = fs.readFileSync('./txt/input.txt', 'utf-8');
console.log(textSync);

// Async- non Blocking Code
fs.readFile('./txt/start.txt', 'utf-8', (err, data) => {
    if(err){ 
    console.log(err);
    return;
    }
    console.log(data);
});

Writing Files

To write files synchronously we use writeFileSync() method, the file's location and the content (which can be a string or a variable) are passed as parameters.

Likewise, we use writeFile() method to write files asynchronously, the directory, the content and a callback function are passed as an argument, Each time a file is written, this callback function is activated. It carries an error parameter to handle potential issues.

If the file is already present, then the existing file will be overridden.

const text='Hello World';

// Sync- Blocking Code
fs.writeFileSync('./txt/file.txt', textOut);
console.log('File Written');

// Async- non Blocking Code
fs.writeFile('./txt/file.txt',text, err) => {
    if(err){ 
    console.log(err);
    return;
    }
    console.log('Data written');
});

Deleting Files

Using unlink() method we can delete existing files, and the directory and a callback function are passed as argument, This callback function comes into play during the deletion process, and it includes an error parameter to manage any potential errors that might arise.

fs.unlink('./txt/file.txt',(err)=>{
    if(err){ 
    console.log(err);
    return;
    }
    console.log('File Deleted');
})

Conclusion

Node.js is a runtime environment that lets us use JavaScript on servers. It provides modules, which are like tools, for various tasks such as handling files. The provided modules offer more than just file handling, extending to functionalities like networking, database interactions, and more. This simplifies building websites and applications because it offers ready-made solutions for common server-related challenges.


Connect With Me ๐Ÿ”—

If you're curious about the MERN Stack or just web development in general, I'd love to connect with you! Feel free to reach out if you have questions, want to share experiences or simply want to chat!

LinkedIn: Click Here

Twitter: Click Here

ย