01 Node JS

ยท

7 min read

01 Node JS

"Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to build server-side and networking applications using JavaScript. It's built on the V8 JavaScript engine, which is the same engine used by the Google Chrome browser."

Introduction to Node.js, its features, and use cases.

Features:

  1. Asynchronous and Event-Driven: Non-blocking I/O model enables high concurrency.

  2. JavaScript Everywhere: Enables full-stack JavaScript development.

  3. NPM (Node Package Manager): Largest ecosystem of open-source libraries and tools.

  4. Cross-Platform Compatibility: Runs on Windows, macOS, and Linux.

  5. Scalability and Performance: Well-suited for real-time and high-traffic applications.

  6. Rich Ecosystem: Abundance of frameworks, libraries, and tools.

Use Cases:

  1. Web Servers and APIs: Fast and lightweight server-side applications.

  2. Real-Time Applications: Chat applications, gaming platforms, and collaboration tools.

  3. Microservices Architecture: Scalable, modular, and deployable microservices.

  4. Command-Line Tools: Automation of build processes, testing, and deployment.

  5. IoT (Internet of Things): Lightweight footprint for IoT applications.

  6. Desktop Applications: Cross-platform desktop applications using web technologies.

01 Installation of Node.js and NPM.

node - v

npm - v

03 Node.js Core Modules

  • fs module for file system operations.

  • http module for creating HTTP servers and clients.

  • path module for handling file paths.

  • events module for event-driven programming.

path module

const path = require("path");

let p1 = path.extname("./index.js");
p1 = path.basename("./index.js");
p1 = path.dirname("./index.js");
console.log(p1);
// Require the 'path' module, which provides utilities for working with file and directory paths
const path = require("path")
// Log the 'path' module object to the console
console.log(path);

// Set a variable 'x' to a file name
x = "indexes.html";
// Log the file extension of 'x' using the 'extname' method of the 'path' module
console.log("File extension:", path.extname(x)); // Output: .html

// Demonstrate path joining using the 'join' method of the 'path' module
// This will generate a file path by joining the provided arguments
console.log("a\b\c\d.js");
let y = path.join("a", "b", "c", "d.js")
console.log("Joined path:", y); // Output: a\b\c\d.js

// Log the directory path of the current module
console.log("Directory path:", __dirname); // Output: <current directory path>

// Log the file path of the current module
console.log("File path:", __filename); // Output: <current file path>
FunctionDescriptionExample
path.join([...paths])Joins all given path segments together using the platform-specific separator. Resolves '..' and '.' segments in paths.javascript const path = require('path'); const fullPath = path.join(__dirname, 'folder', 'file.txt');
path.resolve([...paths])Resolves the given sequence of paths or path segments into an absolute path.javascript const path = require('path'); const absolutePath = path.resolve('folder', 'file.txt');
path.dirname(path)Returns the directory name of a path.javascript const path = require('path'); const directory = path.dirname('/path/to/file.txt');
path.basename(path[, ext])Returns the last portion of a path, similar to the Unix basename command.javascript const path = require('path'); const filename = path.basename('/path/to/file.txt');
path.extname(path)Returns the extension of the path.javascript const path = require('path'); const extension = path.extname('/path/to/file.txt');
path.parse(pathString)Returns an object with the parsed components of the path.javascript const path = require('path'); const pathInfo = path.parse('/path/to/file.txt');
path.normalize(path)Normalizes the given path, resolving '..' and '.' segments.javascript const path = require('path'); const normalizedPath = path.normalize('/path/to/../file.txt');

os module

const os = require('os');
console.log(os);
console.log(os.hostname());
console.log(os.platform());
console.log(os.freemem());
console.log(os.homedir());
console.log(os.networkInterfaces());
console.log(os.totalmem());
console.log(os.uptime());
console.log(os.userInfo());
console.log(os.version());

fs module

File Operation Methods :

MethodDescription
fs.writeFile(file, data, options, callback)Asynchronously writes data to a file, creating the file if it does not exist.
fs.readFile(file, options, callback)Asynchronously reads the contents of a file.
fs.appendFile(file, data, options, callback)Asynchronously appends data to a file, creating the file if it does not exist.
fs.unlink(path, callback)Asynchronously removes (deletes) the file specified by path.

writeFile method :

const fs = require('fs')

// fs.writeFile("./notes.txt", "enter text here...", () => {
fs.writeFile("./notes.txt", "enter text here...", (err) => {
    if (err) {
        // throw err;
        throw new Error("err");
    }
    console.log("File Created - using Async method")
});

fs.writeFileSync("./notes2.txt", "kuch bhi..")
console.log("File Created - Sync Method")

console.log("LEARNING FILE SYSTEM")

readFile Method :

// Build In Modules -----------------
const fs = require("fs") // fs means file system

// asynchronous funtion
fs.readFile("./notes.txt", "utf-8", (err, data) => {
    if (err) {
        throw err;
    }
    console.log(data)
})

// synchronous function
let data = fs.readFileSync("./notes.txt", "utf-8");
console.log(data)

// ๐ŸŽฏ shortcut of import- (don't need to write fs again & again) ๐Ÿ”ฝ

const { readFileSync } = require("fs");
const data = readFileSync("./sample.txt", "utf-8");
console.log(data);

appendFile Method :

const fs = require("fs")

// asynchronous funtion
fs.appendFile("./notes.txt", " daaaataaa...", (err) => {
    if (err)
        throw err;

    console.log("Data appended - (Async)")
})

/* Synchronous version of append */
fs.appendFileSync("./notes.txt", "helloo");
console.log("appended")
  • NOTE: โญ Always keep fs sync method in try catch block
const fs = require('fs');

// Asynchronous Function
fs.unlink("./abc.txt", (err) => {
    if (err)
        throw err;
    console.log("File Deleted.")
})

// Synchronuos Function
fs.unlinkSync("./notes.txt");
console.log("File Deleted - using Sync method")

Directory Methods:

MethodDescription
fs.mkdir(path, options, callback)Creates a new directory with the specified path.
fs.readdir(path, options, callback)Reads the contents of a directory specified by path.
fs.rename(oldPath, newPath, callback)Renames a directory from oldPath to newPath.
fs.rmdir(path, options, callback)Removes (deletes) the directory specified by path.

mkdir method :

const fs = require('fs')
const path = require('path')

// fs.mkdir('./a/assets', (err) => {  // ๐Ÿšจ๐Ÿ’€
// Create 'assets' directory asynchronously
fs.mkdir('./assets', (err) => {
    if (err) throw err;
    console.log("Directory Created !")
})

// Create 'images' directory inside 'assets' synchronously
fs.mkdirSync('./assets/images');
console.log("Directory Created (Sync Method)");

// Write content to a file named 'style.css' inside the 'assets/images' directory
fs.writeFileSync(
    path.join(__dirname, "assets", "images", "style.css"), "Styling File"
);

readdir method :

const fs = require('fs'); // Import the fs module

// Synchronously read the contents of the "./assets" directory
const dirs = fs.readdirSync("./assets");
console.log(dirs); // Log the directory contents to the console

// Asynchronously read the contents of the "./assets" directory
fs.readdir("./assets", (err, files) => {
    if (err) throw err; // Handle any errors that occur during the operation
    console.log(files); // Log the directory contents to the console
});

rename method :

const fs = require('fs'); // Import the fs module

// Rename the directory "./assets" to "./newAssest" synchronously
fs.renameSync("./assets", "./newAssest");

// Rename the file "./x.txt" to "./newAssest/x.txt" synchronously
fs.renameSync("./x.txt", "./newAssest/x.txt");

rmdir method :

โญ NOTE: before using fs.rmdir(), ensure โœ”๏ธ the directory is ๐Ÿ—‘๏ธ empty by ๐Ÿงน removing ๐Ÿ“ all files and ๐Ÿ“‚ subdirectories within it.

let fs = require('fs')

fs.rmdirSync("./assets/images")

Project: Generating HTML, CSS, and JS Boilerplate Files ๐Ÿ“œ

// Importing required modules
const fs = require('fs');
const path = require('path');
const os = require('os');

// Getting the user's home directory and desktop path
let home = os.homedir();
const desktopPath = path.join(os.homedir(), 'Desktop');

// Getting the current date for folder naming
const date = new Date();
const _suffix = `${date.getFullYear()}-${date.getMonth()}-${date.getDay()}`;
const folderPath = path.join(desktopPath, `BoilerPlate_${_suffix}`);

// Checking if the folder already exists, if not, create it
if (!fs.existsSync(folderPath)) {
    try {
        fs.mkdir(path.join(folderPath), (err) => {
            if (err) throw err;
            console.log(`"Website" - Folder Created`);
        });
    } catch (err) {
        console.log(err);
    }
}

// Writing HTML, CSS, and JS files to the folder
// Writing HTML file
fs.writeFile(path.join(folderPath, 'index.html'), htmlBoiler, (err) => {
    if (err) throw err;
    // console.log("Content Added to HTML File");
});

// Writing CSS file
fs.writeFile(path.join(folderPath, 'style.css'), cssBoiler, (err) => {
    if (err) throw err;
    // console.log("Content Added to CSS File");
});

// Writing JS file
fs.writeFile(path.join(folderPath, 'script.js'), jsBoiler, (err) => {
    if (err) throw err;
    // console.log("Content Added to JS File");
});

// Logging confirmation message with folder path
console.log("Your Boiler Plate is ready!");
console.log(`You can access the folder from ${folderPath}`);
const htmlBoiler = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <script src="script.js"></script>
</body>
</html>`;

const cssBoiler = `*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,body{
height: 100%;
width: 100%;
background-color: green;
}`;

const jsBoiler = `document.body.innerHTML = "Hello World for js";
console.log("Demo JS file")`;

import & export - creating and using a module

https://krayush1109.hashnode.dev/076-modules-in-javascript

// CREATING A MODULE
let a = 6450;
console.log(a);
console.log(a / 4);

console.log("Welcome to Node JS");

let b = {
    average: (m, n) => {
        console.log((m + n) / 2);
    },
    percent: (m, n) => {
        console.log((m / n) * 100);
    },
}

module.exports = a;
module.exports = b;
// USING A MODULE
const a = require("./index")

console.log("This is APP.JS FILE", a);

const b = require("./index")

b.average(25, 45);
b.percent(50,200)

Simple HTTP Server Setup

// Import the HTTP module
const http = require('http') 

// Create a server instance
const server = http.createServer() 

// Start the server listening on port 5000
server.listen(5000, () => { 
    console.log("Server is Listening...")
})
ย