NodeJS By Examples
NPM Basics
Module Types
- Core Modules -NodeJS
- Community Modules -NPM
- My Modules
Installation
NPM is Node Package Manager. It can easilily install NodeJS module into your NodeJS project.
NPM is installed together with nodeJS.
#apt-get install nodejs
NPM is installed into:
/usr/lib/node_modules/npm/
Customization
npm set init.author.name "Brent Ertz"
npm set init.author.email "brent.ertz@gmail.com"
npm set init.author.url "http://brentertz.com"
also you can use command which will ask you for username, password and email
#npm adduser
Everything goes into ~/.npmrc file.
Usage
All posibilities can be found at https://docs.npmjs.com/
Basic commands:
$npm init -create package.json file
$npm install - installs all modules defined in package.json
$npm install module - installs module locally into your application (project)
$npm install --save module - install module locally and save info into package.json
$sudo npm install -g module -installs module globally into /usr/lib/node_modules/
$npm remove module -removes module locally
#npm remove -g module -removes module globally
Globally means to install module as a root in /usr/lib/npm_modules/ dir. We must be logged as a user root.
$npm config set loglevel [silent | win | error | warn | info | verbose | silly] - logging while execute npm commnd
$npm command -h -shows help
$npm ls -g --depth=0 -lists all global modules, only first level
$npm ls -gl -list all global modules with detailedexplanation
$npm ls -lists local modules
$npm ls -l -list local modules with explanation
$npm update -g -updates local packages
$npm update -update local modules
File node.json
This file contains info about your project.
{
"name": "Project Name",
"version": "1.0.0",
"description": "Some NodeJS examples",
"main": "index.js",
"dependencies": {
"sys": "^0.0.1",
"fs": "*"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
The most important thing is dependencies and it can be defined on the following ways:
- "express": ">= 2.5.0" -install version greater then or equal to 2.5.0
- "express": "2.5.0" -matches exactly version 2.5.0
- "express": "<= 2.5.0" -install version less then or equal to 2.5.0
- "express": "<=2.5.0 >2.1.0" -install version between 2.1.0 and 2.5.0
- "express": "~2.5.0" -find and install nearest to 2.5.0 version
- "express": "^2.5.0" -install version which is compatible with 2.5.0
- "express": "*" -install any version, usually the latest version
- "express": "latest" -install latest version
- "express": "2.x" -install any 2.x version
- "express": "2.x || <3.1.0" -install any 2.x or less then 3.1.0
The easiest way to create package.json is $npm init which is terminal browser wizzard.
If we acidentally delete some of modules just run $npm install and all dependencies will be installed into our project!