Node Package Manager (NPM)

    0 Votes

Congrats on your 1'st NodeJS application. You successfully executed a simple “Hello World” application. In this article, I introduce you to a very useful tool - NPM, the official package manager for NodeJS. Before learning about NodeJS let us see why we need a package manager. It is time for a different HelloWorld application.

Fun Fact:

NPM doesn’t stand for Node Package Manager (as is misconception with many). NPM is just NPM. Don’t believe me? Open https://www.npmjs.com/ and look above the NPM logo. You can see some random 3 words with initials as NPM. Click on it and it changes.

Hello World Application using another file

We will use two files

  1. index.js - This will contain our JavaScript Code

  2. myText.txt - This will contain our text to display

Create a simple text file in your project folder. (~/Document/NodeJS/a4academics/ here) with the following contents:

npm hello world

Next create a JavaScript file - index.js in the same location with the following code:

"use strict"; // Enable Strict Mode
const fs = require('fs'); // Import 'fs' module

let readMyText = function() 
{
	let str = fs.readFileSync("./myTest.txt").tostring(); // Read file from local file system
	console.log(str); //Print the string
};
readMyText();
    

Explanation:

const and let are new keywords introduced in ES6 (2015 release of JavaScript). They are similar to var keywords and are used for variable declaration.

  • Variables declared used const keywords have immutable values i.e. their values cannot be changed after initialisation.
  • Variables declared used let keywords have blocked scope. They are limited to the scope of current block and cannot be accessed outside the current block. Here the variable str cannot be accessed outside the readMyText function.

If we had used

var str = fs.readFileSync(“./myText.txt”).toString();
    

then the variable str can be accessed even outside the readMyText function.

require is a keyword (only in NodeJS) which is used to import code from another JavaScript file.

fs (FileSystem) is a NodeJS core module which provides various functions to read and write files from the local disk.

The fs module exposes a function readFileSync which reads a file and returns a buffer. We convert this buffer to string using .toString() function.

Then we simply display this string using console.log().

npm console log

Now just run this code using:

Cool yeah…!! You can use this to read and write store data in file. (❂‿❂)

2. Lets add some colors to our life

A simple white text is not that interesting to see. Right? So now we will colorize the text we display.

One way is to use native terminal coloring options by using color specifiers in the text. But that would make our text ugly to see while debugging.

Another and a much better way is to use an external module. chalk is an awesome library for NodeJS which can colorize any string.

Now to include the chalk library (hosted on GitHub), you can clone the repository (https://github.com/chalk/chalk) and require its index.js file. This would create problems when dealing with tens of modules. Also updating a module would require manually replacing the files.

OR

Use NPM

NPM is Package Manager for NodeJS. It handles all your modules and Project information for you.

NPM is installed along with NodeJS automatically while installing NodeJS. To check the current version of installed npm use:

npm current version

To enable npm for our project, we need to initialize our project with npm. For this do this in the project’s root directory:

$ npm init
npm init

Fill in the all the information

What npm init does is that it creates a file package.json in your directory. This is the main file which describes your project to npm engine. After execution your package.json file should contain the following:

package json

The file contains a JSON object with the following fields:

  1. name - This is the name for your project. By default it is the name of your current folder. It is used for identifying your project if hosted on npmjs.org

  2. version - The current version of your project.

  3. description - Description of project.

  4. main - This is the entry point of your app. When others require your module in their project, require will import the file specified by this field.

  5. scripts - This is another JSON object containing various scripts. These scripts are used by various deployment services to run different tasks without the need to manually execute each script.

  6. keywords - Keywords which enable efficient searching of your module.

  7. author - Name and email id of the author of this project.

  8. license - The license under which you are releasing this module.

We are done with initialising our npm project. Next we need to add chalk module to our project.

To install any module from npm repository -- Where all the NodeJS modules are hosted, simple use

$ npm install <module_name>

If we add --save flag to the above command, then npm adds the module in the list of dependencies in the package.json file.

package-json-dependencies

So, to install chalk module, we do

From the output, we can infer that chalk is dependent on the modules

  • ansi-styles
  • escape-string-regexp
  • has-ansi (which is dependent on)
    • ansi-regex
  • strip-ansi
  • supports-color

So, all the above modules are also installed.

All these modules are installed in the node_module/ directory which have been created by the npm install command.

Also, your package.json will have added some lines:

Now when you need to install the same module somewhere else, you don’t need to copy the node_modules/ directory. Just copy rest of the files and do

$ npm install

This command will install all the modules specified in the dependencies object in your package.json .

The caret (^) sign signifies that when doing npm install , latest version of the module having version greater than or equal to the given version (here, 1.1.3) will be installed.

Everything done now.

Open index.js file and modify the code as:

"use strict"; // Enable Strict Mode
const fs = require('fs'); // Import 'fs' module
const chalk = require('chalk'); // Import 'chalk' module
let readMyText = function() 
{
	let str = fs.readFileSync("./myText.txt").toStrig();
	let readStr = chalk.red(str);
	console.log(readStr);
};
readMyText();

The chalk module exposes red function to make the string red. Check out the documentation of the modules before using.

On running this script you would get an output like

npm output

There you go…!!! You just added colors to your life.

Popular Videos

communication

How to improve your Interview, Salary Negotiation, Communication & Presentation Skills.

Got a tip or Question?
Let us know

Related Articles

Node.js Introduction & Environment Setup
Global Variables in Node.js
Node.js Callbacks
Event Loop & Event Emitters in Node.js
Node.js Buffers and Streams
Node.js File System & Setting up File Structure