Skip to Content
Course content

145: Working with npm Packages

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 chalk package.
  • Create a script that defines an array of log objects. Each object should have a level (e.g., 'INFO', 'WARN', 'ERROR') and a message.
  • Loop through the array and print the logs to the console.
  • Requirement: Use chalk to make 'INFO' logs green, 'WARN' logs yellow, and 'ERROR' logs red.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.