In the second post in NodePi series, I will share you about NPM and how to use NPM

What is NPM ? 

NPM is the package manager for JavaScript and the world’s largest software registry. Discover packages of reusable code — and assemble them in powerful new ways. It likes Nuget for C# and Composer for PHP.

You can use NPM via 2 Interfaces:

  • Website: you can sign up an account and upload your packages or only access and search necessary packages
  • CLI: you only run the simple command npm 
npm

Work with NPM

 

Step 1: create the project folder

mkdir /home/pi/nodepi
cd /home/pi/nodepi

 

Step 2: Use npm to initiate project

npm init

Next, let’s fill in information of project such as:  name, author, version, . . . 

After all, you have a file called package.json. This file included all config and installed packages of your project.

 

Step 3: Install package with NPM

To install a package, you only run the command below: 

npm install [package_name]

Add parameter –save at the end of command to automatic save packages information to package.json file.

Example: you wan to install underscore package, let’s run: 

npm install underscore --save

DONE ! All installed packages will be in node_modules folder and of course, nobody want to bring this folder to share with friends because it’s more heavy than Sun, Neutron star and Black hole :)))

So, package.json file is enough. You can re-install all packages with package.json file and command npm install.

 

Step 4: Play with this package

  • Create index.js file
nano index.js
  • write this code and save it

var _ = require(“underscore”);

var a = _.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
console.log(a);

  • Run your project with command
node index.js
  • Your result is:
[3, 6, 9]

That’s all ! We found out NPM and try to play with it. 

See you in the next post !

 

Ha Phuong – Mechasolution.