What is Node?
- Node is not a programming language rather runtime environment to run Javascript code
- Browsers provide runtime environment to run javascript.Node uses Chrome v8 engine internally to run js code.
- 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
- 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.
- 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
- 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
- Node variables has 2 scopes –
- Global Scope
- Local Scope or Module Scope
- Variables like Window, Console is global scope as they are accessed globally over broswer
- 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.
- 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
- 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' ] }
- 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.jsvar 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.jsconst logger = require('./logger'); console.log(logger);
Output
{ log: 'Log Me', printLog: [Function: getLoggedValue] }
- 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
- 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.
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
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.
- Path – Using path we are listing the details of the filename
- OS – We check for the total memory and free memory
- File – We list the files in the directory.Always use asynchrounous reading mode(fs.readdir) for file instead of (fs.readFileSync).
- Events
- 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
- We acquire handle of event class using require in EventEmitter
- Create object using new for EventEmitter
- Add the event to listener and define a function which needs to be called when the event gets fired
- Adding the event could be done using addListener and also by using on method
- 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
- We have a logger.js which is a utility class with log method in it
- We call the log method from eventList class by importing the Logger Class
- 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"]