{"id":689,"date":"2013-02-08T07:20:12","date_gmt":"2013-02-08T07:20:12","guid":{"rendered":"http:\/\/codeatelier.wordpress.com\/?p=461"},"modified":"2019-07-03T12:38:14","modified_gmt":"2019-07-03T12:38:14","slug":"nodejs-concepts","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/nodejs-concepts\/","title":{"rendered":"Node Concepts"},"content":{"rendered":"<p><strong class=\"ctaHeader3\">What is Node?<\/strong><\/p>\n<ol>\n<li>Node is not a programming language rather runtime environment to run Javascript code<\/li>\n<li>Browsers provide runtime environment to run javascript.Node uses Chrome v8 engine internally to run js code.<\/li>\n<li>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 <em>Blocking and Synchronous <\/em>in nature<\/li>\n<li>In node there is single thread and all these request would be served by this single thread hence its is <em>Nonblocking and Asynchronous<\/em> in nature.<\/li>\n<li>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<\/li>\n<li>Since node application runs in an environment outside broswer it provides file handling operations which are not possible by browsers.<\/li>\n<\/ol>\n<p><strong  class=\"ctaHeader3\">How the Execution of js files in Node happens<\/strong><\/p>\n<ol>\n<li>Node variables has 2 scopes &#8211;\n<ul>\n<li>Global Scope<\/li>\n<li>Local Scope or Module Scope<\/li>\n<\/ul>\n<\/li>\n<li>Variables like Window, Console is global scope as they are accessed globally over broswer<\/li>\n<li>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.<\/li>\n<li>The below statements are same in node\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n  console.log('Uses console without global prefix');\r\n  global.console.log('Uses console with global prefix');\r\n <\/pre>\n<p><strong> Output<\/strong><\/p>\n<pre>\r\nUses console without global prefix\r\nUses console with global prefix\r\n<\/pre>\n<\/li>\n<li>Let&#8217;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.\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n  console.log(module); \r\n <\/pre>\n<p><strong> Output<\/strong><\/p>\n<pre>\r\nModule {\r\n  id: '.',\r\n  exports: {},\r\n  parent: null,\r\n  filename: 'D:\\\\AngularProjects\\\\NodeServer\\\\index.js',\r\n  loaded: false,\r\n  children: [],\r\n  paths:\r\n   [ 'D:\\\\AngularProjects\\\\NodeServer\\\\node_modules',\r\n     'D:\\\\AngularProjects\\\\node_modules',\r\n     'D:\\\\node_modules' ] }\r\n<\/pre>\n<\/li>\n<li><strong>Exporting Variable  and Function From Module<\/strong><br \/>\nWe 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<br \/>\n<strong>logger.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar log = &quot;Log Me&quot;\r\n\r\nfunction getLoggedValue(message){\r\n    console.log(message);\r\n}\r\n\r\nmodule.exports.log=log;\r\nmodule.exports.printLog=getLoggedValue;\r\n <\/pre>\n<p><strong>index.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst logger = require('.\/logger');\r\nconsole.log(logger.log);\r\nlogger.printLog('Hi there');\r\n<\/pre>\n<p><strong> Output<\/strong><\/p>\n<pre>\r\nLog Me\r\nHi there\r\n<\/pre>\n<p>You can see what is imported simply by using below statement in index.js<br \/>\n<strong>index.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst logger = require('.\/logger');\r\nconsole.log(logger);\r\n<\/pre>\n<p><strong> Output<\/strong><\/p>\n<pre>\r\n{ log: 'Log Me', printLog: [Function: getLoggedValue] }\r\n<\/pre>\n<li>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<\/li>\n<p><strong>logger.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nvar log = &quot;Log Me&quot;\r\n\r\nfunction getLoggedValue(message){\r\n    console.log(message);\r\n}\r\n\r\nmodule.exports=getLoggedValue;\r\n<\/pre>\n<p><strong>index.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst logger = require('.\/logger');\r\nlogger('Hi there');\r\n<\/pre>\n<p><strong> Output<\/strong><\/p>\n<pre>\r\nHi there\r\n<\/pre>\n<\/li>\n<li>Node always executes modules inside immediately invokable function expression.It is called <strong>Module Wrapper Function<\/strong>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n(function(exports, require, module, __filename, __dirname) {\r\n\/\/ Module code actually lives in here\r\n});\r\n<\/pre>\n<p>Before a module&#8217;s code is executed, Node.js will wrap it with a function wrapper that looks like the following:<br \/>\nBy 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.<br \/>\nIt 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&#8217;s absolute filename and directory path.<\/p>\n<\/li>\n<\/ol>\n<p><strong  class=\"ctaHeader3\">Modules in Node<\/strong><br \/>\nNode is a combination of different modules we interact with based on our needs. Below are a few of them as listed. <\/p>\n<ol>\n<li>Path &#8211; Using path we are listing the details of the filename<\/li>\n<li>OS &#8211; We check for the total memory and free memory<\/li>\n<li>File &#8211; We list the files in the directory.Always use asynchrounous reading mode(fs.readdir) for file instead of (fs.readFileSync). <\/li>\n<li><a href=\"#EVNTMOD\">Events<\/a><\/li>\n<li><a href=\"#HTTPMOD\">Http<\/a><\/li>\n<\/ol>\n<p><strong>index.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconsole.log('-------Path module-------');\r\nconst path = require('path');\r\nvar pathObj = path.parse(__filename);\r\nconsole.log(pathObj);\r\n\r\nconsole.log('------OS module--------');\r\nconst os = require('os');\r\nvar totalMem = os.totalmem();\r\nvar freeMem = os.freemem();\r\nconsole.log(`Total Memory -  ${totalMem}`);\r\nconsole.log(`Free Memory -  ${freeMem}`);\r\n\r\nconsole.log('------FS Module--------');\r\nconst fs = require('fs');\r\nfs.readdir('.\/', (err, files)=&gt;{\r\n    if(err)\r\n     console.log('Error', err);\r\n    else \r\n     console.log('Files', files);\r\n});\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\n-------Path module-------\r\n{ root: 'D:\\\\',\r\n  dir: 'D:\\\\AngularProjects\\\\NodeServer',\r\n  base: 'index.js',\r\n  ext: '.js',\r\n  name: 'index' }\r\n\r\n------OS module--------\r\nTotal Memory -  8465264640\r\nFree Memory -  1929568256\r\n\r\n------FS Module--------\r\nFiles [ 'index.js', 'logger.js', 'package-lock.json', 'test.html' ]\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\"><a name=\"EVNTMOD\">Event Module<\/a><\/strong><br \/>\nEvent is a singnal which tells something has happened.Below is a simple code for event listener<\/p>\n<ol>\n<li>We acquire handle of event class using require in EventEmitter<\/li>\n<li>Create object using new for EventEmitter<\/li>\n<li>Add the event to listener and define a function which needs to be called when the event gets fired<\/li>\n<li>Adding the event could be done using addListener and also by using on method<\/li>\n<li>Emit the event using emit methid<\/li>\n<\/ol>\n<p><strong>index.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst EventEmitter = require('events');\r\nconst emitter = new EventEmitter();\r\n\r\nemitter.addListener('Message Listener', ()=&gt;console.log('Listener Called'));\r\nemitter.emit('Message Listener');\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nListener Called\r\n<\/pre>\n<p>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.<br \/>\n<strong>index.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst EventEmitter = require('events');\r\nconst emitter = new EventEmitter();\r\n\r\nemitter.addListener('Message Listener', (argObj)=&gt;{\r\n                                                    console.log(argObj.argument1);\r\n                                                    console.log(argObj.argument2);\r\n                                                  });\r\nemitter.emit('Message Listener', {'argument1':'arg1 val', 'argument2':'arg2 val'});\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\narg1 val\r\narg2 val\r\n<\/pre>\n<p>Now let&#8217;s build a custom class which does the logging<\/p>\n<ol>\n<li>We have a logger.js which is a utility class with log method in it<\/li>\n<li>We call the log method from eventList class by importing the Logger Class<\/li>\n<li>In the logger we extend event emitter and use this reference to call the eventEmitter<\/li>\n<\/ol>\n<p><strong>logger.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst EventEmitter = require('events');\r\n\r\nclass Logger extends EventEmitter\r\n{\r\n    log(strLogMessage)\r\n    {\r\n        this.emit('MessageListener', strLogMessage);        \r\n    }\r\n}\r\n\r\nmodule.exports = Logger;\r\n<\/pre>\n<p><strong>eventList.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst Logger = require('.\/logger');\r\n\r\nconst objLogger = new Logger(); \r\n\r\nobjLogger.addListener('MessageListener', (arg) =&gt;{console.log(arg)});\r\nobjLogger.log('Calling the Log Method');\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nCalling the Log Method\r\n<\/pre>\n<p><strong  class=\"ctaHeader3\"><a name=\"HTTPMOD\">HTTP Module<\/a><\/strong><br \/>\n<strong>server.js<\/strong><\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nconst http = require('http');\r\n\r\nconst server = http.createServer();\r\n\r\nconst server = http.createServer((req, res)=&gt;{\r\n    if(req.url === '\/')\r\n    {\r\n        res.write('Hello World...');\r\n        res.end();\r\n    }\r\n\r\n    if(req.url === '\/api\/customers')\r\n    {\r\n        res.write(JSON.stringify(&#x5B;'Customer1', 'Customer2', 'Customer3']));\r\n        res.end();\r\n    }\r\n});\r\n\r\nserver.listen(3000);\r\nconsole.log('Listening on Port 3000.....');\r\n<\/pre>\n<p><strong>Input and Output<\/strong><\/p>\n<pre>\r\nIP : http:\/\/localhost:3000\/\r\nOP : Hello World...\r\n\r\nIP : http:\/\/localhost:3000\/api\/customers\r\nOP : [\"Customer1\",\"Customer2\",\"Customer3\"]\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>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&hellip; <a href=\"https:\/\/codethataint.com\/blog\/nodejs-concepts\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[139],"tags":[],"class_list":["post-689","post","type-post","status-publish","format-standard","hentry","category-node-js"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/689","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=689"}],"version-history":[{"count":20,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/689\/revisions"}],"predecessor-version":[{"id":3537,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/689\/revisions\/3537"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=689"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=689"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=689"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}