Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 9 - Packages

9.1 Overview

In JavaScript and Node.js, packages are collections of reusable code modules that can be easily shared and integrated into various projects.

Why Packages are Used

Packages are used to add specific functionalities to a project without having to write the code from scratch. They can include anything from utility functions and frameworks to complete libraries for handling complex tasks like database interactions or web server management.

Types of Packages

  • Built-in Packages: Node.js comes with a set of built-in packages that provide core functionalities, such as http, fs, and path. These are part of the Node.js runtime and do not need to be installed separately.
  • External Packages: These are packages created by the community and can be added to a project using the package.json file. External packages are typically installed via package managers like npm or Yarn.

Example of Built-in Package in Node.js

// Import the built-in fs package
const fs = require('fs');

// Read the contents of the file example.txt
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }
  console.log('File contents:', data);
});

The example above uses the built-in fs package, which provides functionality to read and write data to files. We will use this package to read a file and print its contents.