Node.js #Day 1: Unraveling File Handling Magic & Basics of Node.js

Day#1 Node.js: Basics of Node.js, File handling, Modules, Package.json

Sandeep Singh (Full Stack Dev.)
5 min readAug 12, 2023
Day #1 Node.js series

Hello there👋, future Node.js maestros! I’m thrilled to embark on this learning journey with you.

As a seasoned Node.js developer, I understand the challenges that beginners might face while diving into the world of server-side JavaScript.

But fret not — I’m here to guide you through every intricate concept, making sure you grasp them with crystal clarity.

By the time we’re done, you’ll wield the power of Node.js to create stunning web applications. So, let’s get started!

As this is the Day#1 of this Node.js Series, Before going deep into Nodejs, I want to introduce some basic overviews which are really important before creating servers, APIs , backend development. So this article will be about some basic concept overviews.

Remember: This is just Day#1, after covering some basic concepts we will gonna start backend development with Nodejs, Express.js, mongoDB and build various real world projects in it.

Note: Tutorial videos will also published within 1–2 days after this article published

Unveiling the Magic of Node.js

Before we delve into the nitty-gritty details, let’s uncover the magic of Node.js.

Imagine having a single programming language, JavaScript, that bridges the gap between client and server. With Node.js, that dream becomes reality.

It’s like having a versatile toolkit that empowers you to craft not just the front-end but also the back-end of web applications. Exciting, right?

The Heart of Node.js: Modules

Alright, let’s talk about the heart of Node.js — modules. Think of modules as self-contained units of code that make your life easier.

They allow you to break down your application into manageable pieces. Imagine you’re building a house — each module is like a room, contributing to the whole structure. You can create your own modules or leverage the vast Node.js community’s offerings.

Creating Your First Module

Suppose you’re building an e-commerce website, and you want to calculate the total price of items in the cart. Let’s create a cart.js module:

// cart.js
module.exports.calculateTotal = function(items) {
let total = 0;
items.forEach(item => {
total += item.price;
});
return total;
};

Now, in your main application file:

// app.js
const cart = require('./cart');
const items = [
{ name: 'Shirt', price: 25 },
{ name: 'Jeans', price: 40 },
{ name: 'Shoes', price: 60 }
];
const totalPrice = cart.calculateTotal(items);
console.log(`Total Price: $${totalPrice}`);

Voilà! You’ve created and utilized your first Node.js module.

Navigating the NPM Universe

Time to meet your best friend in the Node.js ecosystem — NPM (Node Package Manager). NPM is a treasure trove of pre-built packages that add functionality to your projects. Imagine it’s like a gigantic toolbox that you can explore to find the perfect tool for your task.

Installing and Using Packages

Let’s say you’re developing a weather app and want to fetch weather data from an API. Instead of writing all the API handling code from scratch, you can use the axios package:

npm install axios

Now, you can use axios to fetch data in your app:

const axios = require('axios');
axios.get('https://api.weather.com/data').then(response => {
console.log(response.data);
}).catch(error => {
console.error('Error fetching data:', error);
});

NPM simplifies your life by providing ready-to-use tools for various tasks. Just remember to include them in your package.json for future reference.

The File System Awakens

Now, let’s dive into something practical — the file system. In real-world applications, reading and writing files is a common task. Node.js equips you with the ‘fs’ module to interact with the file system.

Note: Remeber this is only Day#1, so You don’t need to understand about ‘fs’ Module in depth, I am making tutorial video, there i have explained in detailed about fs Module, how it works? how to use? and other modules also… Just wait for the video, It will published within 2 days

For now just understand how modules works and how we can use it in javascript and how you can use ‘fs’ module to create and write files

Reading and Writing Files

Imagine you’re building a notes app. You can use the ‘fs’ module to create, read, and update notes stored in files. Let’s create a notes.txt file:

how to use fs module in javascript
file read and write using javascript

Imagine ‘fs’ as your personal assistant for handling files. It helps you write and read stuff from files.

In the first part, we wrote “Hello, world!” in a file named ‘notes.txt’.

Then, in the second part, we read what we wrote and saved it in the content variable.

Finally, when we print out content, it shows "Hello, world!" – just like a magic trick where your assistant brings out the exact thing you asked for from a hidden box!

So, in a nutshell, we used the ‘fs’ module to write and read from a file, and what we wrote magically appeared when we read it back. Cool, right? Now you have a tiny glimpse of the behind-the-scenes magic in coding!

This is just the tip of the iceberg when it comes to working with files. The ‘fs’ module provides a plethora of functions for different file operations.

The Power of package.json

The package.json file is like the blueprint of your project. It holds crucial information about your application, including its dependencies and scripts.

Crafting Your package.json

When you create a new project, you can generate a package.json file using:

npm init

As you install packages, they are automatically added to your dependencies. For example, if you install Express.js:

npm install express

It gets listed in your package.json:

"dependencies": {
"express": "^4.17.1"
}

Conclusion

Congratulations, dear learners! You’ve embarked on a thrilling Node.js adventure, unraveling modules, harnessing the power of NPM, mastering the file system, and understanding the significance of package.json. These concepts are the building blocks of your journey to becoming a proficient Node.js developer.

Remember, practice is key. Try building small projects, explore the vast NPM ecosystem, and experiment with modules. Don’t hesitate to dive deeper into Node.js’s intricacies as you gain confidence. With each step, you’re leveling up your skills and becoming an unstoppable force in the world of web development.

Keep coding, keep exploring, and most importantly, keep nurturing your passion for learning. Your journey has just begun, and the possibilities are limitless.

FAQs

What if I don’t understand modules at first?

No worries! Think of modules as Lego bricks. It might seem confusing at first, but as you build more, the picture becomes clear.

I’m overwhelmed by the NPM universe. Where do I start?

Start with small projects. As you encounter challenges, search for related NPM packages. You’ll gradually become more comfortable.

How can I become a Node.js master?

Practice, patience, and curiosity are your allies. Keep coding, read documentation, and learn from others in the community.

What if my package.json becomes messy?

Keep it clean! Regularly review your dependencies, remove unused packages, and maintain a clear structure.

Any advice for tackling the file system complexities?

Start small. Create a simple file manipulation project and gradually add complexity. Experimenting is the key to mastering it.

--

--

Sandeep Singh (Full Stack Dev.)

Fullstack Developer | MERN & Flutter | Passionate about Open Source | Engaged in Contributing & Collaborating for a Better Tech Community. 🚀