2024-11-15
If you’ve installed Node.js, npm usually comes bundled with it. To verify your installation and check the version, open your terminal and run:
npm -vThis will output the installed npm version. If you don’t have npm installed, you’ll need to download and install Node.js from the official website: https://nodejs.org/
npm init: Creating a package.json fileThe package.json file is the heart of your Node.js project. It lists project metadata, dependencies, and scripts. To create one, navigate to your project directory in the terminal and run:
npm init -yThe -y flag automatically accepts the default values. You can omit this to manually configure each setting. This will generate a package.json file containing basic information about your project.
npm install: Installing PackagesThis is arguably the most frequently used npm command. It installs packages from the npm registry (npmjs.com). To install a package, for example, express (a popular web framework), use:
npm install expressThis command downloads express and its dependencies and adds them to your project’s node_modules folder. It also updates your package.json file to list express as a dependency under the dependencies section.
To install a package as a development dependency (only needed for development, not production), use the --save-dev flag or -D:
npm install --save-dev nodemonnodemon is a tool that restarts your server automatically on code changes, useful during development.
npm install with package.jsonIf you have a package.json file with dependencies listed, you can install all of them at once:
npm installThis is particularly useful when sharing your project with others; they can simply run this command to set up the project’s environment.
npm uninstall: Removing PackagesTo remove a package, use:
npm uninstall expressThis removes the package from node_modules and updates the package.json file.
npm list: Viewing Installed PackagesTo see all the installed packages, including their dependencies, use:
npm listThis provides a tree-like structure showing all installed packages and their versions.
npm update: Updating PackagesTo update all the packages listed in package.json to their latest versions, use:
npm updateYou can update specific packages using:
npm update expressnpm run: Running Scripts Defined in package.jsonThe scripts section in package.json allows you to define custom commands. For example:
{
"name": "my-project",
"version": "1.0.0",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
}You can then run these scripts using:
npm run start // Runs node server.js
npm run dev // Runs nodemon server.jsThese examples demonstrate the fundamental commands. npm offers many more features, including package versioning (using semver), managing private packages, and working with different registries, providing a flexible system for managing your Node.js project dependencies.