Getting Started with Node.js : A Beginner’s Guide

PRIYAM MONDAL
4 min readMay 28, 2023

--

Node.js is a powerful runtime environment that allows you to build scalable and efficient server-side applications using JavaScript. It is built on Chrome’s V8 JavaScript engine and provides a rich set of features and libraries that make it an excellent choice for web development. In this article, we will explore the basics of Node.js and its key features, covering important concepts such as modules, file system operations, path manipulation, and creating a simple HTTP server.

Table of Contents:

  1. What is Node.js?
  2. Installing Node.js
  3. Creating and Exporting Modules
  4. Working with the File System
  5. Manipulating File Paths
  6. Interacting with the Operating System
  7. Building a Simple HTTP Server

What is Node.js?

Node.js is a server-side JavaScript runtime environment that allows you to run JavaScript code outside of a web browser. It provides a non-blocking, event-driven architecture, making it highly efficient for handling concurrent operations. With Node.js, you can build server applications, command-line tools, real-time applications, and more.

Installing Node.js:

To get started with Node.js, you need to install it on your system. Visit the official Node.js website (https://nodejs.org) and download the appropriate installer for your operating system. Follow the installation instructions to set up Node.js on your machine.

Creating and Exporting Modules:

Node.js follows the CommonJS module system, which allows you to split your code into reusable modules. In the provided code snippets, you can see an example of exporting and importing a module using module.exports and require().

// index.js
// Exporting module to use it in another folder
const info = {
name: "Priyam Mondal",
age: 24,
profession: "Software Engineer",
};

module.exports = info;

// To access the module "info" that was exported from "index.js" we have two methods

// 1. old school require() => this will not work inside a module,
// use it in normal .js file
// app.js

const info = require("./index.js");
console.log("info => ", info);

// 2. import statement => this will not work outside module,
// to make your file a module, instead writing your file extension .js use .mjs
// app.mjs

import info from "./index.js"
console.log("info => ", info);

Working with the File System:

Node.js provides a built-in module called fs for working with the file system. You can perform various file operations such as reading files asynchronously using fs.readFile(), reading files synchronously using fs.readFileSync(), writing files asynchronously using fs.writeFile(), and writing files synchronously using fs.writeFileSync(). To append data to an existing file we can use fs.appendFile() . To delete a file we can use fs.unLink().The code snippets demonstrate how to use these methods.

// index.js

const fs = require("fs");

// Asynchronously read a file
fs.readFile("./test.txt", "utf8", (err, data) => {
if (err) {
throw err;
} else {
console.log(data);
}
});

// Synchronously read a file
const data = fs.readFileSync("./test.txt", "utf8");
console.log(data);

// Asynchronously create a file
const content = "Hey, I want to write something here...";
fs.writeFile("./sampleWrite.txt", content, () => {
console.log("File written!");
});

// Synchronously create a file
const content = "Hey, we have written something in the sampleWrite file, replacing the content!";
fs.writeFileSync("./sampleWrite.txt", content);

// Add some data to a file without deleting existing content
// Suppose we have a file abc.txt and in it a text is written "hellow world"
fs.appendFile("./abc.txt", "This is new content",(err)=>{
console.log(err);
})
//output =>
//hellow world This is new content

// Delete a file
// If you want to delete the abc.txt file
fs.unLink("./abc.txt",(err)=>{
console.log(err)
})

Manipulating File Paths:

The path module in Node.js provides functions for working with file paths. You can extract the file extension using path.extname(), get the base name of a file using path.basename(), and retrieve the directory name using path.dirname(). The examples in the code show how to use these functions.

// index.js

const path = require("path");

const extensionName = path.extname("./sampleWrite.txt");
console.log(extensionName); // .txt

const baseName = path.basename("./sampleWrite.txt");
console.log(baseName); // sampleWrite.txt

const directory = path.dirname("/home/priyam/Desktop/Node Js/test.txt");
console.log(directory); // /home/priyam/Desktop/Node Js

Interacting with the Operating System:

The os module in Node.js provides information about the operating system. You can retrieve details such as total memory using os.totalmem(), free memory using os.freemem(), host name using os.hostname(), and user information using os.userInfo(). The code snippets illustrate the usage of these functions.

// index.js

const os = require("os");

const totalMemory = os.totalmem();
console.log(totalMemory);

const freeMemory = os.freemem();
console.log(freeMemory);

const hostName = os.hostname();
console.log(hostName);

const userInfo = os.userInfo();
console.log(userInfo);

Building a Simple HTTP Server:

Node.js allows you to create web servers easily. In the provided server.js code snippet, we demonstrate how to create a basic HTTP server that handles different routes and sends appropriate responses. The server listens on a specific port and displays a message when it is up and running.

// server.js

const http = require("http");
const fs = require("fs");
const PORT = process.env.PORT || 4040;

const server = http.createServer((req, res) => {
if (req.url === "/") {
const home = fs.readFileSync("./index.html", "utf8");
res.end(home);
} else if (req.url === "/about") {
res.end("<h1>About Page</h1>");
} else if (req.url === "/contact") {
res.end("<h1>Contact Page</h1>");
} else {
res.end("<h1>404 page not found!</h1>");
}
});

server.listen(PORT, () => {
console.log(`Server is up and running on port ${PORT}`);
});

Node.js opens up exciting possibilities for web development, enabling developers to leverage their JavaScript skills both on the front end and the back end. With its event-driven architecture and extensive set of features, you can build robust and high-performance applications using Node.js. So, get started with Node.js today and unlock the full potential of JavaScript on the server!

--

--

PRIYAM MONDAL
PRIYAM MONDAL

Written by PRIYAM MONDAL

Full Stack Developer | React.js | Express.js | MongoDB | MySQL | Node.js

No responses yet