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

Lesson 9 - Packages

9.2 Installing and Using Packages

To manage Node.js packages, we utilize npm or yarn. While npm is the default package manager, yarn serves the same purpose.

To install packages, we first initialize the project.

Initializing a Project

Start by setting up the project:

npm init

This action creates a package.json file, containing project metadata.

Example of package.json

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "A simple project",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "eslint": "^7.32.0"
  },
  "author": "Your Name",
  "license": "MIT"
}

Installing a Package

To add a package, execute:

npm install express

This installs express and includes it in node_modules.

Uninstalling a Package

To remove a package, use:

npm uninstall express

Using a Package

After installation, import the package:

const express = require('express');

Now, express is ready for use in your project.

const express = require('express');
const app = express();

Some packages, like readline, are included in Node.js by default, requiring no separate installation.