There are two ways to install npm packages: local or global. You can choose which installation to use based on the package you want to use.
If you want to rely on your own modules to use a Node.js-like require, then you want to install locally, which is the default behavior of npm install. On the other hand, if you want to use it as a command line tool, like the grunt CLI, then you want to install it globally.
Installation
A package can be downloaded with the following command:
This will create node_modules directory in the current directory if it doesn't already exist and download the package to that directory.
Test:
To confirm that npm install is working, check if the node_modules directory exists and that it contains the directory of the package you installed. You can run ls node_modules on a Unix system to do this job. "OSX", "Debian" or dir node_modules on Windows.
Example:
Install a package called lodash. Confirm that it is running successfully by listing the contents of node_modules directory and looking at the directory named lodash.
If you don't have package.json file in your local directory, install the latest version of the package.
If there is a package.json or package-lock.json file, then the latest version, if any, that satisfies the semver rules declared in the package.json will be installed.
Use the installed package
Once the package is in the node_modules, you can use it in your code. For example, if you're creating a Node.js module, you can request it.
Example:
Create a file called index.js with the following code:
The correct output result is: [2, 3]
If you don't install lodash correctly, you get this error:
If you had not properly installed lodash, you would receive this error:
module.js:340 throw err; ^
Error: Cannot find module 'lodash' To fix this, run npm install lodash in the directory where your index.js is located.
|