Monday, June 29, 2015

Non-blocking, require and modules in node.js

node.js is very close to JavaScript and it's also server side JavaScript. We can run js files once we have node installed in our machine using:

node app.js 

There are lot of differences too between node and JavaScript. node.js does not use "window" as a global variable, but it uses "global" as global variable. However, console is common object which is used across both of them. 

node is Non blocking: 

nodejs is non-blocking means if we create a server using node.js and are listening to any port, we can handle as many as request we want. Server will not blocked to a particular request, it can get request from all other client with out getting blocked. Same is true for any database request. 

require in node: 

require is used to import any module in node. It searches the file, folder or core modules to import. Order of searching for module is as follows: 

Let say we import module using require('./info') 
  • node will search for info.js file for module, if found then it will import it's functions 
  • If file with info.js is not found, node will look for folder with info name followed by index.js in that that folder 
  • If module is imported like require('info'), node will consider it as core module or project level module 

Module in node: 

We can create module in node using module.exports or exports.function_name . Setting module.exports allows the database_module function to be called like a function when required. Simply setting exports wouldn't allow the function to be exported.  

Method 1: The following code will allow the user to call the function 

Method 2: The following code wouldn't allow the user to call the function, but call it using object