RK !

Let's make comprehension easy ...

100%x200

NodeJS

Author: Romaan, Last Updated: March 2, 2017, 4:20 a.m.

NodeJS is an open-source, cross-platform JavaScript runtime environment for developing a diverse variety of server tools and applications. It is based on event-driven, non blocking I/O model. It uses a single thread, using non-blocking I/O calls, allowing it to support tens of thousands of concurrent connections without incurring the cost of thread context switching.

Require and Exports

In Node, things are only visible to other things in the same file. By things, I mean variables, functions, classes and class members. So, given a file misc.js with the following contents:

var x = 5;
var addX = function(value) {
  return value + x;
};


Another file cannot access the x variable or addX function. This has nothing to do with the use of the var keyword. Rather, the fundamental Node building block is called a module which maps directly to a file. So we could say that the above file corresponds to a module named file1 and everything within that module (or any module) is private.

Now, before we look at how to expose things out of a module, let's look at loading a module. This is where require comes in. require is used to load a module, which is why its return value is typically assigned to a variable:

var misc = require('./misc');


Of course, as long as our module doesn't expose anything, the above isn't very useful. To expose things we use module.exports and export everything we want:

var x = 5;
var addX = function(value) {
  return value + x;
};
module.exports.x = x;
module.exports.addX = addX;


Now we can use our loaded module:

var misc = require('./misc');
console.log("Adding %d to 10 gives us %d", misc.x, misc.addX(10));


There's another way to expose things in a module:

var User = function(name, email) {
  this.name = name;
  this.email = email;
};
module.exports = User;


The difference is subtle but important. See it? We are exporting user directly, without any indirection. The difference between:

module.exports.User = User;
//vs
module.exports = User;


is all about how it's used:

var user = require('./user');
var u = new user.User();
//vs
var u = new user();


It's pretty much a matter of whether your module is a container of exported values or not. You can actually mix the two within the same module, but I think that leads to a pretty ugly API.

Finally, the last thing to consider is what happens when you directly export a function:

var powerLevel = function(level) {
  return level > 9000 ? "it's over 9000!!!" : level;
};
module.exports = powerLevel;


When you require the above file, the returned value is the actual function. This means that you can do:

require('./powerlevel')(9050);


Which is really just a condensed version of:

var powerLevel = require('./powerlevel')
powerLevel(9050);

 

Comments: