Wednesday, April 15, 2020

What is Node Package Manager?

Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls Node.js packages in your application. It is also an online repository for open-source Node.js packages. The node community around the world creates useful modules and publishes them as packages in this repository.
It has now become a popular package manager for other open-source JavaScript frameworks like AngularJS, jQuery, Gulp, Bower etc.
Official website: https://www.npmjs.com
NPM is included with Node.js installation. After you install Node.js, verify NPM installation by writing the following command in terminal or command prompt.
C:\> npm -v
2.11.3

If you have an older version of NPM then you can update it to the latest version using the following command.
C:\> npm install npm -g
To access NPM help, write npm help in the command prompt or terminal window.
C:\> npm help
NPM performs the operation in two modes: global and local. In the global mode, NPM performs operations which affect all the Node.js applications on the computer whereas in the local mode, NPM performs operations for the particular local directory which affects an application in that directory only.

Install Package Locally

Use the following command to install any third party module in your local Node.js project folder.
C:\>npm install <package name>
For example, the following command will install ExpressJS into MyNodeProj folder.
C:\MyNodeProj> npm install express
All the modules installed using NPM are installed under node_modules folder. The above command will create ExpressJS folder under node_modules folder in the root folder of your project and install Express.js there.

Add Dependency into package.json

Use --save at the end of the install command to add dependency entry into package.json of your application.
For example, the following command will install ExpressJS in your application and also adds dependency entry into the package.json.
C:\MyNodeProj> npm install express --save
The package.json of NodejsConsoleApp project will look something like below.
package.json
{
  "name": "NodejsConsoleApp",
  "version": "0.0.0",
  "description": "NodejsConsoleApp",
  "main": "app.js",
  "author": {
    "name": "Dev",
    "email": ""
  },
  "dependencies": {
    "express": "^4.13.3"
  }
}

Install Package Globally

NPM can also install packages globally so that all the node.js application on that computer can import and use the installed packages. NPM installs global packages into /<User>/local/lib/node_modules folder.
Apply -g in the install command to install package globally. For example, the following command will install ExpressJS globally.
C:\MyNodeProj> npm install -g express

Update Package

To update the package installed locally in your Node.js project, navigate the command prompt or terminal window path to the project folder and write the following update command.
C:\MyNodeProj> npm update <package name>
The following command will update the existing ExpressJS module to the latest version.
C:\MyNodeProj> npm update express

Uninstall Packages

Use the following command to remove a local package from your project.
C:\>npm uninstall <package name>
The following command will uninstall ExpressJS from the application.
C:\MyNodeProj> npm uninstall express

What is Export Module in Node.js?

In the previous section, you learned how to write a local module using module.exports. In this section, you will learn how to expose different types as a module using module.exports.
The module.exports or exports is a special object which is included in every JS file in the Node.js application by default. module is a variable that represents current module and exports is an object that will be exposed as a module. So, whatever you assign to module.exports or exports, will be exposed as a module.
Let's see how to expose different types as a module using module.exports.

Export Literals

As mentioned above, exports is an object. So it exposes whatever you assigned to it as a module. For example, if you assign a string literal then it will expose that string literal as a module.
The following example exposes simple string message as a module in Message.js.
Message.js
module.exports = 'Hello world';

//or

exports = 'Hello world';
Now, import this message module and use it as shown below.
app.js
var msg = require('./Messages.js');

console.log(msg);
Run the above example and see the result as shown below.
C:\> node app.js
Hello World

Note: You must specify './' as a path of root folder to import a local module. However, you do not need to specify path to import Node.js core module or NPM module in the require() function.

Export Object

exports is an object. So, you can attach properties or methods to it. The following example exposes an object with a string property in Message.js file.
Message.js
exports.SimpleMessage = 'Hello world';

//or

module.exports.SimpleMessage = 'Hello world';
In the above example, we have attached a property "SimpleMessage" to the exports object. Now, import and use this module as shown below.
app.js
var msg = require('./Messages.js');

console.log(msg.SimpleMessage);
In the above example, require() function will return an object { SimpleMessage : 'Hello World'} and assign it to the msg variable. So, now you can use msg.SimpleMessage.
Run the above example by writing node app.js in the command prompt and see the output as shown below.
C:\> node app.js
Hello World

The same way as above, you can expose an object with function. The following example exposes an object with log function as a module.
Log.js
module.exports.log = function (msg) { 
    console.log(msg);
};
The above module will expose an object- { log : function(msg){ console.log(msg); } } . Use the above module as shown below.
app.js
var msg = require('./Log.js');

msg.log('Hello World');
Run and see the output in command prompt as shown below.
C:\> node app.js
Hello World

You can also attach an object to module.exports as shown below.
data.js
module.exports = {
    firstName: 'James',
    lastName: 'Bond'
}
app.js
var person = require('./data.js');
console.log(person.firstName + ' ' + person.lastName);
Run the above example and see the result as shown below.
C:\> node app.js
James Bond

Export Function

You can attach an anonymous function to exports object as shown below.
Log.js
module.exports = function (msg) { 
    console.log(msg);
};
Now, you can use the above module as below.
app.js
var msg = require('./Log.js');

msg('Hello World');
The msg variable becomes function expression in the above example. So, you can invoke the function using parenthesis (). Run the above example and see the output as shown below.
C:\> node app.js
Hello World

Export function as a class

In the JavaScript, a function can be treated like a class. The following example exposes a function which can be used like a class.
Person.js
module.exports = function (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = function () { 
        return this.firstName + ' ' + this.lastName;
    }
}
The above module can be used as shown below.
app.js
var person = require('./Person.js');

var person1 = new person('James', 'Bond');

console.log(person1.fullName());
As you can see, we have created a person object using new keyword. Run the above example as below.
C:\> node app.js
James Bond

In this way, you can export and import a local module created in a separate file under root folder.
Node.js also allows you to create modules in sub folders. Let's see how to load module from sub folders.

Load Module from Separate Folder

Use the full path of a module file where you have exported it using module.exports. For example, if log module in the log.js is stored under "utility" folder under the root folder of your application then import it as shown below.
app.js
var log = require('./utility/log.js');
In the above example, . is for root folder and then specify exact path of your module file. Node.js also allows us to specify the path to the folder without specifying file name. For example, you can specify only utility folder without specifing log.js as shown below.
app.js
var log = require('./utility');
In the above example, Node will search for a package definition file called package.json inside utility folder. This is because Node assumes that this folder is a package and will try to look for a package definition. The package.json file should be in a module directory. The package.json under utility folder specifies the file name using "main" key as below.
./utility/package.json
{
    "name" : "log",
    "main" : "./log.js"
}
Now, Node.js will find log.js file using main entry in package.json and import it.
 Note:
If package.json file does not exist then it will look for index.js file as a module file by default.

What is Node.js Local Module?

Local modules are modules created locally in your Node.js application. These modules include different functionalities of your application in separate files and folders. You can also package it and distribute it via NPM, so that Node.js community can use it. For example, if you need to connect to MongoDB and fetch data then you can create a module for it, which can be reused in your application.

Writing Simple Module

Let's write simple logging module which logs the information, warning or error to the console.
In Node.js, module should be placed in a separate JavaScript file. So, create a Log.js file and write the following code in it.
Log.js
var log = {
            info: function (info) { 
                console.log('Info: ' + info);
            },
            warning:function (warning) { 
                console.log('Warning: ' + warning);
            },
            error:function (error) { 
                console.log('Error: ' + error);
            }
    };

module.exports = log
In the above example of logging module, we have created an object with three functions - info(), warning() and error(). At the end, we have assigned this object to module.exports. The module.exports in the above example exposes a log object as a module.
The module.exports is a special object which is included in every JS file in the Node.js application by default. Use module.exports or exports to expose a function, object or variable as a module in Node.js.
Now, let's see how to use the above logging module in our application.

Loading Local Module

To use local modules in your application, you need to load it using require() function in the same way as core module. However, you need to specify the path of JavaScript file of the module.
The following example demonstrates how to use the above logging module contained in Log.js.
app.js
var myLogModule = require('./Log.js');

myLogModule.info('Node.js started');
In the above example, app.js is using log module. First, it loads the logging module using require() function and specified path where logging module is stored. Logging module is contained in Log.js file in the root folder. So, we have specified the path './Log.js' in the require() function. The '.' denotes a root folder.
The require() function returns a log object because logging module exposes an object in Log.js using module.exports. So now you can use logging module as an object and call any of its function using dot notation e.g myLogModule.info() or myLogModule.warning() or myLogModule.error()
Run the above example using command prompt (in Windows) as shown below.
C:\> node app.js
Info: Node.js started

Thus, you can create a local module using module.exports and use it in your application.
Let's see how to expose different types as a node module using module.exports in the next section.

Node.js Module

Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript files which can be reused throughout the Node.js application.
Each module in Node.js has its own context, so it cannot interfere with other modules or pollute global scope. Also, each module can be placed in a separate .js file under a separate folder.
Node.js implements CommonJS modules standard. CommonJS is a group of volunteers who define JavaScript standards for web server, desktop, and console application.

Node.js Module Types

Node.js includes three types of modules:
  1. Core Modules
  2. Local Modules
  3. Third Party Modules

Node.js Core Modules

Node.js is a light weight framework. The core modules include bare minimum functionalities of Node.js. These core modules are compiled into its binary distribution and load automatically when Node.js process starts. However, you need to import the core module first in order to use it in your application.
The following table lists some of the important core modules in Node.js.
Core ModuleDescription
httphttp module includes classes, methods and events to create Node.js http server.
urlurl module includes methods for URL resolution and parsing.
querystringquerystring module includes methods to deal with query string.
pathpath module includes methods to deal with file paths.
fsfs module includes classes, methods, and events to work with file I/O.
utilutil module includes utility functions useful for programmers.

Loading Core Modules

In order to use Node.js core or NPM modules, you first need to import it using require() function as shown below.
var module = require('module_name');
As per above syntax, specify the module name in the require() function. The require() function will return an object, function, property or any other JavaScript type, depending on what the specified module returns.
The following example demonstrates how to use Node.js http module to create a web server.
Example: Load and Use Core http Module
var http = require('http');

var server = http.createServer(function(req, res){

  //write code here

});

server.listen(5000); 
In the above example, require() function returns an object because http module returns its functionality as an object, you can then use its properties and methods using dot notation e.g. http.createServer().
In this way, you can load and use Node.js core modules in your application. We will be using core modules throughout these tutorials.
Learn about local modules in the next section.

Node.js Basics

Node.js supports JavaScript. So, JavaScript syntax on Node.js is similar to the browser's JavaScript syntax.
Visit JavaScript section to learn about JavaScript syntax in detail.

Primitive Types

Node.js includes following primitive types:
  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • RegExp
Everything else is an object in Node.js.

Loose Typing

JavaScript in Node.js supports loose typing like the browser's JavaScript. Use var keyword to declare a variable of any type.

Object Literal

Object literal syntax is same as browser's JavaScript.
Example: Object
var obj = {
    authorName: 'Ryan Dahl',
    language: 'Node.js'
}

Functions

Functions are first class citizens in Node's JavaScript, similar to the browser's JavaScript. A function can have attributes and properties also. It can be treated like a class in JavaScript.
Example: Function
function Display(x) { 
    console.log(x);
}

Display(100);

Buffer

Node.js includes an additional data type called Buffer (not available in browser's JavaScript). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network.

process object

Each Node.js script runs in a process. It includes process object to get all the information about the current process of Node.js application.
The following example shows how to get process information in REPL using process object.
> process.execPath
'C:\\Program Files\\nodejs\\node.exe'
> process.pid
1652
> process.cwd()
'C:\\'

Defaults to local

Node's JavaScript is different from browser's JavaScript when it comes to global scope. In the browser's JavaScript, variables declared without var keyword become global. In Node.js, everything becomes local by default.

Access Global Scope

In a browser, global scope is the window object. In Node.js, global object represents the global scope.
To add something in global scope, you need to export it using export or module.export. The same way, import modules/object using require() function to access it from the global scope.
For example, to export an object in Node.js, use exports.name = object.
Example:
exports.log = {
    console: function(msg) {
        console.log(msg);
    },
    file: function(msg) {
        // log to file here
      }
}
Now, you can import log object using require() function and use it anywhere in your Node.js project.
Learn about modules in detail in the next section.

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...