require module does not respond object as singleton pattern in some cases - node.js

file_a.js is dependency of file_b.js and file_c.js. Please take a look in file_c.js, there is weird thing there.
file_a.js
module.exports = {
test: null,
setTest: function(a){
this.test = a;
},
getTest: function(){
return this.test
},
}
file_b.js
var a = require('./file_a')
var b = {
print: function(someVar){
console.log(someVar);
}
}
a.setTest(b)
file_c.js
this way will work
var a = require('./file_a')
console.log(typeof a.getTest().print) //function
this way will NOT work
var a = require('./file_a').getTest()
console.log(typeof a.print) //Cannot read property 'print' of null

Both of your examples for file_c.js throw TypeError: Cannot read property 'print' of null.
Module from file_b.js sets test property from module file_a.js on its initialization, and in your snippets it never gets initialized. To fix this, you need:
var a = require('./file_a');
require('./file_b'); // now `test` is set
console.log(typeof a.getTest().print); // function
or
require('./file_b'); // module from `file_a` loaded to cache and `test` is set
var a = require('./file_a').getTest();
console.log(typeof a.print); // function

Related

When exporting a module like this, what happens?

I was looking up some database connection Google searches when I saw something that exported an instance of a module as such
const foo = () => {
// Do stuff
};
...
module.exports = foo();
I don't know what this is called but how does nodejs treat exporting a function invocation vs an object or the function itself (without calling it)?
Thank you
The foo function only gets called once no matter how many times you require the module.
This is very simplified explanation of what is happening behind the scenes in Node.js
// cache for modules
var modules = {};
// very simplified require function
function require(name) {
// check cache
if (modules[name])
// so if it has already been required it returns the cached result
return modules[name].module.exports;
// it will resolve path to the required module
// and loads the file content
// not showing here
var obj = { module: { exports: {}}};
// node will wrap the code in a function similar to bellow
function module(module, exports){
const foo = () => {
// Do stuff
};
...
module.exports = foo();
};
module(obj.module, obj.module.exports);
// and now cache it
modules[name] = obj;
return obj.module.exports;
}

node.js module export how to use data amoung all modules?

I would like to use updated (and only then) globals among all node modules. How to do that? Questions are in code.
app.js
var data = 'data';
var global = require('glob.js')(data);
// here we are require your globals variables and we corectly 'set them'
console.log(globals.glob1);
// we can use them here
glob.js
module.exports = function(data)
{
var globs = {
glob1 : data.toLowerCase(),
glob2 : data.toUpperCase()
}
return globs;
}
mod.js
var global = require('glob.js'); // I require globals but they are not set...
function funct(someOtherData, someMoreData)
{
var test = global.glob1;
console.log(test);
// why I can't use globals here ? How can I use corectly set globals (globals need to be updated first - app.js, then ALL other modules should be able to use correctly set globals)?
}
module.export = funct;
For the answer scroll down to the TLDR section below but do read on to understand why.
Part1 - the difference between a function and a function call
Your first mistake is that you are exporting a function, not an object:
module.exports = function(data) // <---- this is a function
{
var globs = {
glob1 : data.toLowerCase(),
glob2 : data.toUpperCase()
}
return globs;
}
and in app.js you do this:
console.log(globs.glob1); <--- globs is a function, not an object
when you should be doing this:
console.log(globs().glob1);
Why is this? OK, lets forget for a moment your module. Consider the following code:
var a = function(){ return 2 };
console.log(a); // do you expect this to print a function or 2?
console.log(a()); // what do you expect this to print?
This is a very basic rule about functions in all programming languages, not just javascript: to get the return value you need to call the function. So in your code:
function myExportedFunction (data) {
// some logic here...
return globs;
}
console.log(myExportedFunction); // prints a function
console.log(myExportedFunction()); // prints the globs object
console.log(myExportedFunction().glob1); // prints value of glob1
So it's simple really. There is no magic syntax going on. You've just forgotten to return the glob object and are using the function pointer instead. Obviously the function has no glob1 property so it's correct for it to be undefined.
Part2 - function local variables
OK. So let's say you made the changes I recommended above. There's an obvious problem with the way the function was written. What happens when you do this:
var glob = require('glob.js')();
console.log(glob.glob1); // <--- prints "undefined"
So the first problem is you're not checking if you're passing data or nothing. So every time you call the function you will overwrite the stored value.
There's another problem, you are always returning a different object every time you call the function. Let's look at how local variables work when returned:
function a () {
var data = {}
return data;
}
var x = a();
var y = a();
x.testing = 1;
y.testing = 2;
console.log(x.testing); // prints 1
console.log(y.testing); // prints 2
So, every time you call a function that creates a local variable you are returning a different object. Actually what's doing this is not really the variable but the object literal syntax:
var a = {};
// is basically the same as
var a = new Object();
If we change the above example to:
function a () {
return {};
}
it would still behave the same.
TLDR
So, how do we fix it? Simple, create the object outside of the function and check if we pass data to initialize:
var globs = {
glob1 : "",
glob2 : ""
}
module.exports = function(data)
{
globs.glob1 = data.toLowerCase();
globs.glob2 = data.toUpperCase();
return globs;
}
Now everything should work:
In app.js
var global = require('glob.js')(data);
In mod.js
var global = require('glob.js')();
Epologue - modules are singletons
It may or may not be obvious to you why the above should work. In case you already know why I'm writing this as reference to future readers.
In node.js modules are implemented as proper singletons. Therefore in node if you want a singleton all you need to do is write a module, you don't need to implement any special code for it.
What this means is that all module globals (module scoped variables) are shared amongst all requires. Here's a very simple module to share one variable amongst all modules:
shared.js
var x = "";
module.exports = {
set: function (val) {x=val},
get: function () {return x}
}
a.js
var shared = require('./shared');
shared.set("hello world");
b.js
var shared = require('./shared');
console.log(shared.get()); // prints "hello world"
We're using this feature to declare a shared glob variable in the code above.
You can use the global. variable identifier to set global variables in NodeJS, instead of var, example:
app.js
var data = 'data';
var glob = require('./glob.js');
glob(data);
// here we are require your globals variables and we corectly 'set them'
console.log(global.gl.glob1);
var mod = require('./mod.js');
mod();
// we can use them here
glob.js
module.exports = function(data)
{
console.log("setting globals");
global.gl = {
glob1 : '1' + data,
glob2 : '2' + data
}
// return global.gl; // can be removed
}
mod.js
function funct(someOtherData, someMoreData)
{
var test = global.gl.glob1;
console.log(test);
test = global.gl.glob2;
console.log(test);
// why I can't use globals here ? How can I use corectly set globals (globals need to be updated first - app.js, then ALL other modules should be able to use correctly set globals)?
}
module.exports = funct;
As you can see in glob.js, i switched to var globs = to global.gl = and then in mod.js used it as global.gl.
Running app.js outputs:
setting globals
1data // From app.js
1data // From mod.js imported in app.js
2data // From mod.js imported in app.js
There are 2 options:
Use nodejs global variable (not recommended)
Create shared module
You chose 2nd option, but did it a bit wrong way by exporting a function. When you import the package and call the function it always creates new globs object and fulfill it with your data. Instead you can export an object. Simple example
glob.js
Global object is defined here
module.exports = {
glob1: '1',
glob2: '2'
};
mod.js
You can change global object here, like
var globs = require('./glob');
module.exports.updateGlob1 = function(data) {
globs.glob1 = data;
};
app.js
Here if you access global variable you can see it updated
var globs = require('./glob');
var mod = require('./mod');
mod.updateGlob1('1 plus 2');
console.log(globs.glob1); // Output: '1 plus 2'
There can be more complex examples, as for module design pattern often IIFE is used.
UPDATE
Another example using IIFE.
glob.js
module.exports = (function() {
var glob1 = 'initial value';
return {
// Getter method
getGlob1() {
return glob1;
},
// Setter method
setGlob1(value) {
glob1 = value;
}
}
})();
mod.js
var shared = require('./shared');
module.exports.testFn = function() {
// Access global variable with getter method
console.log('In mod.js', shared.getGlob1());
};
app.js
var shared = require('./shared');
var mod = require('./mod');
// Print initial value
console.log('Initial', shared.getGlob1());
// Set new value to global variable
shared.setGlob1('new value');
// Print updated value
console.log('In app.js', shared.getGlob1());
// Use global variable in mod.js file
mod.testFn();

Getting instance of node module while test driving codeal

I am creating a factory method where i am returning an instance of a node module
var dal1 = require('../dal/dal1');
var dal2 = require('../dal/dal2');
exports.createDAL(role){
switch(role){
case "XYZ": return dal1;
case "ABC": return dal2
}
};
Using Mocha as the TDD frame work, When I get the object returned,I get the value of returnObject.constructor.name as object instead of dal1 or dal2. Any pointers?
So I went ahead with using the node-module 'util'. I was able to get the expected value instead of just 'Object'
I created a DAL object
//dal.js
function dal(){
}
dal.prototype.BLAH = function(){
//logic here
}
module.exports = dal
//dal1.js
var inherits = require('util').inherits;
function dal1(){
dal1.call(this);
}
inherits(dal1,dal);
module.exports = dal1;
//similarly dal2.js
//finally in factory
var dal1 = require('./dal1');
var dal2 = require('./dal2');
switch(role){
case 'XYZ': return new dal1();
case 'ABC' : return new dal2();
}

pass optional parameters to require()

so, I have this problem - and when I have a problem with JavaScript or node inevitably it is my coding that is the problem ;)
So at the risk of ridicule, this is the problem:
I have a module that has an optional parameter for config
Using the standard pattern, this is what I have:
module.exports = function(opts){
return {
// module instance
};
}
and in the calling code there is this
var foo = require('bar')({option: value})
if there are no options to pass, the code looks like this
var foo = require('bar')({})
which kinda looks ugly
so, I wanted to do this
var foo = require('bar')
which doesn't work, as the exports is a function call
so, to the meat of the issue
a) is there any way of achieving this lofty goal ?
b) is there a better pattern of passing parameters to a module ?
many thanks - and I hope that once the laughter has passed you will be able to send some help my way :)
Instead of removing the function call completely, you could make the options argument options to remove the need for an empty object:
module.exports = function(opts) {
opts = opts || {};
return {
// module instance
};
}
It doesn't completely remove the need for () but is better than ({}).
tldr: stick with require('foo')('bar');
There's no way to pass additional parameters to require. Here's the source code, notice how it only takes a single argument:
Module.prototype.require = function(path) {
assert(util.isString(path), 'path must be a string');
assert(path, 'missing path');
return Module._load(path, this);
};
If you really really really want to avoid ()(), you could try something like this:
b.js
'use strict';
module.exports = {
x: 'default',
configure: function (x) {
this.x = x;
},
doStuff: function () {
return 'x is ' + this.x;
}
};
a.js
'use strict';
var b = require('./b');
// Default config:
console.log(b.doStuff()); // 'x is default'
// Reconfigure:
b.configure(42);
console.log(b.doStuff()); // 'x is 42'
But I think it's uglier... stick with the original idea.

solving circular dependency in node using requirejs

I have been try out many suggestions I found googling for circular dependency in node and requirejs. Unfortunately, I'm not getting it to work. The try which is closed to a solution (I think) is below:
// run.js
var requirejs = require('requirejs');
requirejs.config({
baseUrl: __dirname,
nodeRequire: require
});
requirejs(['A'], function(A) {
var a = new A.Go();
console.log(a.toon())
});
// A.js
define(['B', 'exports'], function(B, exports) {
exports.Go = function() {
var b = new require('B').Ho();
var toon = function() {
return 'me tarzan';
};
return {
b: b,
toon: toon
}
};
});
// B.js
define(['A', 'exports'], function(A, exports) {
exports.Ho = function() {
var a = new require('A').Go();
var show = function() {
return 'you jane';
}
return {
a: a,
show: show
}
};
});
Running this code in node results in a RangeError: Maximum call stack size exceeded
We the dependency of B is removed from A.js, 'me tarzan' is returned
Any suggestion is appreciated!
Circular references are fine and not necessarily a symptom of bad design. You might argue that having many tiny modules could be equally detrimental because code/logic is scattered.
To avoid the dreaded TypeError: Object #<Object> has no method you need to take some care in how you initialize module.exports. I'm sure something similar applies when using requirejs in node, but I haven't used requirejs in node.
The problem is caused by node having an empty reference for the module. It is easily fixed by assigning a value to the exports before you call require.
function ModuleA() {
}
module.exports = ModuleA; // before you call require the export is initialized
var moduleB = require('./b'); //now b.js can safely include ModuleA
ModuleA.hello = function () {
console.log('hello!');
};
This sample is from https://coderwall.com/p/myzvmg where more info available.

Resources