JavaScript
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Types
-
Section 3: Strings and Numbers in Depth
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Objects and Arrays
-
Section 7: Maps, Sets, and Symbols
-
Section 8: Asynchronous JavaScript
-
Section 9: Object-Oriented and Prototypes
-
Section 10: The DOM
-
Section 11: Browser APIs
-
Section 12: Modern JavaScript (ES2015-ES2025)
-
Section 13: Functional Programming Patterns
-
Section 14: Error Handling and Debugging
-
Section 15: Testing
-
Section 16: Accessibility for JavaScript Developers
-
Section 17: Internationalization and Localization
-
Section 18: Performance
-
Section 19: Node.js Fundamentals
-
Section 20: Regular Expressions
-
Section 21: Design Patterns in JavaScript
-
Section 22: Security Basics
-
Section 23: Data Structures and Algorithms in JavaScript
-
Section 24: Practical Projects
-
Section 25: More Advanced Async Patterns
-
Section 26: More Object and Class Practice
-
Section 27: Working with Dates and Internationalization
-
Section 28: Web Components
-
Section 29: More DOM and Browser Practice
-
Section 30: Build Tooling for Vanilla JavaScript
-
Section 31: More Practice Projects
-
Section 32: Interview and Algorithm Practice
-
Section 33: Error Objects (MDN Reference)
-
Section 34: TypedArrays and Binary Data
-
Section 35: Reflection and Metaprogramming (MDN Reference)
-
Section 36: More Global Functions (MDN Reference)
145: Working with npm Packages
You've probably noticed by now that JavaScript's native Date object is... well, a bit of a nightmare. If you've ever tried to calculate the difference between two dates or format a timestamp into something a human actually wants to read, you know exactly how frustrating it gets. This is where npm packages come in. Instead of reinventing the wheel, we can lean on the community.
Setting up the project and pulling in date-fns
I want to build a small utility that takes a timestamp and tells us how long ago it happened—like "3 days ago" or "about 2 hours ago." For this, I'm going to use date-fns. I prefer it over the older moment.js because it's modular, meaning we only import the specific functions we need, which keeps our final bundle size small.
First, I'll initialize the project and install the package:
npm init -y
npm install date-fns
Now we have a node_modules folder and a package.json file. The package.json is the most important part here; it's the manifest that tells anyone else working on this project exactly which dependencies they need to install to make the code run.
Making a date feel human
I'll create a file called timeAgo.js. I want to use the formatDistanceToNow function from the library. Here is my first attempt at the logic:
const { formatDistanceToNow } = require('date-fns');
const postDate = "2023-12-01T10:00:00Z";
const relativeTime = formatDistanceToNow(postDate, { addSuffix: true });
console.log(`Post created ${relativeTime}`);
When I run this with node timeAgo.js, it crashes immediately. I get a TypeError: Invalid time value. I paused for a second and realized I made a classic mistake: I passed a string directly into the function. date-fns expects a proper JavaScript Date object, not an ISO string.
To fix this, I need to wrap that string in a new Date() constructor. Let's correct that:
const { formatDistanceToNow } = require('date-fns');
const postDateString = "2023-12-01T10:00:00Z";
const postDate = new Date(postDateString); // Fix: Convert string to Date object
const relativeTime = formatDistanceToNow(postDate, { addSuffix: true });
console.log(`Post created ${relativeTime}`);
Now it works perfectly. It prints something like "Post created 5 months ago." (Depending on when you run it, of course).
Refining the imports for efficiency
One thing I want to mention is how I imported the function. Using require('date-fns') and destructuring is fine for small scripts, but in a massive production app, you'd want to be even more specific to help the build tool "tree-shake" the code (remove unused parts). In a modern ESM environment, I'd do something like import { formatDistanceToNow } from 'date-fns/formatDistanceToNow'. For this simple Node script, the destructuring we used is more than enough, but keep that in mind as you move into larger frameworks like React or Vue.
📋 Practical Task
The Colorful System Log Formatter
Your goal is to create a small Node.js script that formats system logs using the chalk npm package to add color to the output.
- Initialize a new npm project in a fresh folder.
- Install the
chalkpackage. - Create a script that defines an array of log objects. Each object should have a
level(e.g., 'INFO', 'WARN', 'ERROR') and amessage. - Loop through the array and print the logs to the console.
- Requirement: Use
chalkto make 'INFO' logs green, 'WARN' logs yellow, and 'ERROR' logs red.
There are no comments for now.