Welcome to our Node.js tutorial series! Today, we're diving into npm (Node Package Manager), an essential tool for every Node.js developer. Let's get started!
npm is a package manager for Node.js. It helps us to manage and share open-source packages easily. With npm, you can download and install thousands of reusable packages for your projects, saving you time and effort.
Before you can use npm, you need to install it on your system. If you already have Node.js installed, npm comes bundled with it. To check if npm is installed, run this command in your terminal or command prompt:
npm -vIf you don't have Node.js installed, download it from the official website.
Let's explore how to use npm in your projects. We'll create a simple Node.js application and install a package called express, a popular web framework.
Create a new folder for your project and navigate into it:
mkdir my-project && cd my-projectInitialize your project with npm by running the following command:
npm initYou'll be asked to enter various details about your project. You can accept the defaults by pressing Enter for each question.
Now, let's install express using npm:
npm install expressOnce installed, you can require it in your code:
const express = require('express');
const app = express();
// Your code hereYou can search for packages on the npm registry using the following command:
npm search <package-name>To install a specific version of a package, use:
npm install <package-name>@<version>npm scripts allow you to define custom commands for your projects. To create a script, add it to the scripts section in your project's package.json file:
{
"scripts": {
"start": "node app.js"
}
}Now, you can run this script with the following command:
npm run startnpm keeps track of your project's dependencies in the package.json file. When you share your project with others, they can easily install the required dependencies using npm.
What does npm stand for?
How do you install npm?
That's it for our npm introduction! In the next lesson, we'll dive deeper into npm and learn how to create, publish, and manage our own packages. Stay tuned! 🎉