module.exports
. Speaking of amusing , I hint that this is, after all, one of the fundamental parts of Node.js and it is quite simple. Looking back now, I cannot explain why it stopped me so much ... I just remember that this moment was not obvious to me. Well, I suppose that I am one of those many who, having met him once or twice, at first only got confused, before writing something using it.misc.js
follows: var x = 5; var addX = function(value) { return value + x; };
x
and the function addX
from another file is not possible. This has nothing to do with the use of var
. The fact is that Node consists of blocks called modules , and each individual file is inherently a separate block, whose scope is isolated from other similar blocks. require
is written. require
use to load a module, usually assigning the result of its work to some variable: var misc = require('./misc');
module.exports
: var x = 5; var addX = function(value) { return value + x; }; module.exports.x = x; module.exports.addX = addX;
var misc = require('./misc'); console.log(" %d 10 %d", misc.x, misc.addX(10));
var User = function(name, email) { this.name = name; this.email = email; }; module.exports = User;
module.exports.User = User; //vs module.exports = User;
var user = require('./user'); var u = new user.User(); //vs var u = new user();
var powerLevel = function(level) { return level > 9000 ? "it's over 9000!!!" : level; }; module.exports = powerLevel;
require
, in fact it will be a function that allows you to do the following: require('./powerlevel')(9050);
var powerLevel = require('./powerlevel') powerLevel(9050);
Source: https://habr.com/ru/post/217901/
All Articles