1. Node Package manager is a package manager which ships along node
  2. It is a Javascript package manager which helps to manage modules like HTTP, Event etc..
  3. Once the npm init is run package.json would be created in the project folder.It is similar to pom.xml for Maven project which saves all the settings and dependencies
  4. To check the npm version
    >>npm -v 
    >>npm --version
    
  5. To create a new project we use the below command – take default setting by telling -yes
    >>npm init -yes
    
  6. To Install a new package is as below
    >>npm install NAME_OF_PACKAGE
    
  7. To Set particular config name
    >>npm set CONFIG_KEY CONFIG_VALUE
    >>npm set init-licencse "MIT"
    
  8. To Get particular config name
    >>npm get CONFIG_KEY 
    >>npm get init-licencse
    
  9. To Install a new package
    >>npm install packagename
    >>npm install loadash
    

    Running the above command is going to create a node_modules folder in project with the dependencies for the package(loadash) installed.

  10. To Install only dependencies that are needed to run app other than utility dependencies like gulp which provides minified version of JS use below command
    >>npm install --production
    
  11. To remove dependencies
    >>npm remove gulp
    
  12. To install specific version
    >>npm install gulp@4.7.3
    
  13. To update latest version
    >>npm update gulp
    
  14. Semantic versioning formart.PatchVersion includes bug fixes and minor tweaks
    MajorVersion.MinorVersion.PatchVersion
    4.7.8
    
  15. How to find the location of node modules
    >>npm root -g
    

    This will take you to location C:\Users\Mugil\AppData\Roaming\npm\node_modules

  16. How to install server globally – live-server will reload the JS files without restart of server
    >>npm install -g live-server
    

    This will take you to location C:\Users\Mugil\AppData\Roaming\npm\node_modules

  17. When you move the project to new environment no need to move the node_modules folder similar to avoiding JAR while shifting java application.We just need to move the JS file and package.json which contains the details of dependencies. Running npm install will read the package.json file and load the dependencies in new environment

package.json

   "name": "my_package",
    "description": "",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "dependencies": {"loadash" : 14.7.8},
    "keywords": [],
    "author": "",
    "license": "ISC",
    "bugs": {
      "url": "https://github.com/ashleygwilliams/my_package/issues"
    },
    "homepage": "https://github.com/ashleygwilliams/my_package"
  }

How to run some js file in the beginning of the server
I have JS server which needs to start at the beginning of application. In such case I would be defining the JS file in scripts.
You need to call npm start after chaning package.json file
package.json

.
.
"scripts": {
      "start": "node server.js"
    }
.
.

Let’s create a simple application which greets with Welcome message in console on start
package.json

{
  "name": "school",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "Mugil",
  "license": "ISC"
}

index.js

console.log('Welcome to School .....');

output

Welcome to School .....

package.json
live-server allows you to run code without restarting server after changes.

.
.
"scripts": {
    "start": "node index.js",
    "server": "live-server"
  }
.
.
>>npm run server

What is Node?

  1. Node is not a programming language rather runtime environment to run Javascript code
  2. Browsers provide runtime environment to run javascript.Node uses Chrome v8 engine internally to run js code.
  3. In Traditional server request are assigned a thread and the response would be server. So there exist one thread for each request.The threads cannot be shared and Blocking and Synchronous in nature
  4. In node there is single thread and all these request would be served by this single thread hence its is Nonblocking and Asynchronous in nature.
  5. Because of this asynchronous nature node is not suitable for Data intensive operations and for image manipulation, Since the threads would be locked for a long time
  6. Since node application runs in an environment outside broswer it provides file handling operations which are not possible by browsers.

How the Execution of js files in Node happens

  1. Node variables has 2 scopes –
    • Global Scope
    • Local Scope or Module Scope
  2. Variables like Window, Console is global scope as they are accessed globally over broswer
  3. In Node everything is a module. Each js file would be accounted for as a module. The js file execution happens within its own module scope.
  4. The below statements are same in node
      console.log('Uses console without global prefix');
      global.console.log('Uses console with global prefix');
     

    Output

    Uses console without global prefix
    Uses console with global prefix
    
  5. Let’s try to print the module variable in Node js using below code.The code below prints the details of the module such as js file name, exports done from module and so on.
      console.log(module); 
     

    Output

    Module {
      id: '.',
      exports: {},
      parent: null,
      filename: 'D:\\AngularProjects\\NodeServer\\index.js',
      loaded: false,
      children: [],
      paths:
       [ 'D:\\AngularProjects\\NodeServer\\node_modules',
         'D:\\AngularProjects\\node_modules',
         'D:\\node_modules' ] }
    
  6. Exporting Variable and Function From Module
    We exported a variable and a function from logger.js and we called the same in index.js.Now when you run console.log(module) we can see the exported functionality in exports
    logger.js

    var log = "Log Me"
    
    function getLoggedValue(message){
        console.log(message);
    }
    
    module.exports.log=log;
    module.exports.printLog=getLoggedValue;
     

    index.js

    const logger = require('./logger');
    console.log(logger.log);
    logger.printLog('Hi there');
    

    Output

    Log Me
    Hi there
    

    You can see what is imported simply by using below statement in index.js
    index.js

    const logger = require('./logger');
    console.log(logger);
    

    Output

    { log: 'Log Me', printLog: [Function: getLoggedValue] }
    
  7. In case you are having just a single function the same thing can be accessed in the imported js as below. Let export just a single function in logger.js
  8. logger.js

    var log = "Log Me"
    
    function getLoggedValue(message){
        console.log(message);
    }
    
    module.exports=getLoggedValue;
    

    index.js

    const logger = require('./logger');
    logger('Hi there');
    

    Output

    Hi there
    
  9. Node always executes modules inside immediately invokable function expression.It is called Module Wrapper Function
    (function(exports, require, module, __filename, __dirname) {
    // Module code actually lives in here
    });
    

    Before a module’s code is executed, Node.js will wrap it with a function wrapper that looks like the following:
    By doing this, Node.js achieves a few things:It keeps top-level variables (defined with var, const or let) scoped to the module rather than the global object.
    It helps to provide some global-looking variables that are actually specific to the module. The module and exports objects that the implementor can use to export values from the module.The convenience variables __filename and __dirname, containing the module’s absolute filename and directory path.

Modules in Node
Node is a combination of different modules we interact with based on our needs. Below are a few of them as listed.

  1. Path – Using path we are listing the details of the filename
  2. OS – We check for the total memory and free memory
  3. File – We list the files in the directory.Always use asynchrounous reading mode(fs.readdir) for file instead of (fs.readFileSync).
  4. Events
  5. Http

index.js

console.log('-------Path module-------');
const path = require('path');
var pathObj = path.parse(__filename);
console.log(pathObj);

console.log('------OS module--------');
const os = require('os');
var totalMem = os.totalmem();
var freeMem = os.freemem();
console.log(`Total Memory -  ${totalMem}`);
console.log(`Free Memory -  ${freeMem}`);

console.log('------FS Module--------');
const fs = require('fs');
fs.readdir('./', (err, files)=>{
    if(err)
     console.log('Error', err);
    else 
     console.log('Files', files);
});

Output

-------Path module-------
{ root: 'D:\\',
  dir: 'D:\\AngularProjects\\NodeServer',
  base: 'index.js',
  ext: '.js',
  name: 'index' }

------OS module--------
Total Memory -  8465264640
Free Memory -  1929568256

------FS Module--------
Files [ 'index.js', 'logger.js', 'package-lock.json', 'test.html' ]

Event Module
Event is a singnal which tells something has happened.Below is a simple code for event listener

  1. We acquire handle of event class using require in EventEmitter
  2. Create object using new for EventEmitter
  3. Add the event to listener and define a function which needs to be called when the event gets fired
  4. Adding the event could be done using addListener and also by using on method
  5. Emit the event using emit methid

index.js

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.addListener('Message Listener', ()=>console.log('Listener Called'));
emitter.emit('Message Listener');

Output

Listener Called

Lets try to pass arguments to event listener. Arguments should always be passed as JSON Objects as as one parameter inorder to avoid confusion though passing as a individual argument is going to work fine.
index.js

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.addListener('Message Listener', (argObj)=>{
                                                    console.log(argObj.argument1);
                                                    console.log(argObj.argument2);
                                                  });
emitter.emit('Message Listener', {'argument1':'arg1 val', 'argument2':'arg2 val'});

Output

arg1 val
arg2 val

Now let’s build a custom class which does the logging

  1. We have a logger.js which is a utility class with log method in it
  2. We call the log method from eventList class by importing the Logger Class
  3. In the logger we extend event emitter and use this reference to call the eventEmitter

logger.js

const EventEmitter = require('events');

class Logger extends EventEmitter
{
    log(strLogMessage)
    {
        this.emit('MessageListener', strLogMessage);        
    }
}

module.exports = Logger;

eventList.js

const Logger = require('./logger');

const objLogger = new Logger(); 

objLogger.addListener('MessageListener', (arg) =>{console.log(arg)});
objLogger.log('Calling the Log Method');

Output

Calling the Log Method

HTTP Module
server.js

const http = require('http');

const server = http.createServer();

const server = http.createServer((req, res)=>{
    if(req.url === '/')
    {
        res.write('Hello World...');
        res.end();
    }

    if(req.url === '/api/customers')
    {
        res.write(JSON.stringify(['Customer1', 'Customer2', 'Customer3']));
        res.end();
    }
});

server.listen(3000);
console.log('Listening on Port 3000.....');

Input and Output

IP : http://localhost:3000/
OP : Hello World...

IP : http://localhost:3000/api/customers
OP : ["Customer1","Customer2","Customer3"]