Node.js "require" function and parameters - javascript

When I do:
lib = require('lib.js')(app)
is app actually geting passed in?
in lib.js:
exports = module.exports = function(app){}
Seems like no, since when I try to do more than just (app) and instead do:
lib = require('lib.js')(app, param2)
And:
exports = module.exports = function(app, param2){}
I don't get params2.
I've tried to debug by doing:
params = {}
params.app = app
params.param2 = "test"
lib = require("lib.js")(params)
but in lib.js when I try to JSON.stringify I get this error:
"DEBUG: TypeError: Converting circular structure to JSON"

When you call lib = require("lib.js")(params)
You're actually calling lib.js with one parameter containing two properties name app and param2
You either want
// somefile
require("lib.js")(params);
// lib.js
module.exports = function(options) {
var app = options.app;
var param2 = options.param2;
};
or
// somefile
require("lib.js")(app, param2)
// lib.js
module.exports = function(app, param2) { }

You may have an undefined value that you're trying to pass in.
Take for instance, requires.js:
module.exports = exports = function() {
console.log('arguments: %j\n', arguments);
};
When you call it correctly, it works:
node
> var requires = require('./requires')(0,1,2,3,4,5);
arguments: {"0":0,"1":1,"2":2,"3":3,"4":4,"5":5}
If you have a syntax error, it fails:
> var requires = require('./requires')(0,);
... var requires = require('./requires')(0,2);
...
If you have an undefined object, it doesn't work:
> var requires = require('./requires')(0, undefined);
arguments: {"0":0}
So, I'd first check to see that your object is defined properly (and spelled properly when you pass it in), then check that you don't have syntax errors.

Related

JavaScript NodeJs - TypeError X is not a constructor [duplicate]

I've been working with nodejs lately and still getting to grips with the module system, so apologies if this is an obvious question. I want code roughly like the below:
a.js (the main file run with node)
var ClassB = require("./b");
var ClassA = function() {
this.thing = new ClassB();
this.property = 5;
}
var a = new ClassA();
module.exports = a;
b.js
var a = require("./a");
var ClassB = function() {
}
ClassB.prototype.doSomethingLater() {
util.log(a.property);
}
module.exports = ClassB;
My problem seems to be that I can't access the instance of ClassA from within an instance of ClassB.
Is there any correct / better way to structure modules to achieve what I want?
Is there a better way to share variables across modules?
Try to set properties on module.exports, instead of replacing it completely. E.g., module.exports.instance = new ClassA() in a.js, module.exports.ClassB = ClassB in b.js. When you make circular module dependencies, the requiring module will get a reference to an incomplete module.exports from the required module, which you can add other properties latter on, but when you set the entire module.exports, you actually create a new object which the requiring module has no way to access.
While node.js does allow circular require dependencies, as you've found it can be pretty messy and you're probably better off restructuring your code to not need it. Maybe create a third class that uses the other two to accomplish what you need.
[EDIT] it's not 2015 and most libraries (i.e. express) have made updates with better patterns so circular dependencies are no longer necessary. I recommend simply not using them.
I know I'm digging up an old answer here...
The issue here is that module.exports is defined after you require ClassB.
(which JohnnyHK's link shows)
Circular dependencies work great in Node, they're just defined synchronously.
When used properly, they actually solve a lot of common node issues (like accessing express.js app from other files)
Just make sure your necessary exports are defined before you require a file with a circular dependency.
This will break:
var ClassA = function(){};
var ClassB = require('classB'); //will require ClassA, which has no exports yet
module.exports = ClassA;
This will work:
var ClassA = module.exports = function(){};
var ClassB = require('classB');
I use this pattern all the time for accessing the express.js app in other files:
var express = require('express');
var app = module.exports = express();
// load in other dependencies, which can now require this file and use app
Sometimes it is really artificial to introduce a third class (as JohnnyHK advises), so in addition to Ianzz:
If you do want to replace the module.exports, for example if you're creating a class (like the b.js file in the above example), this is possible as well, just make sure that in the file that is starting the circular require, the 'module.exports = ...' statement happens before the require statement.
a.js (the main file run with node)
var ClassB = require("./b");
var ClassA = function() {
this.thing = new ClassB();
this.property = 5;
}
var a = new ClassA();
module.exports = a;
b.js
var ClassB = function() {
}
ClassB.prototype.doSomethingLater() {
util.log(a.property);
}
module.exports = ClassB;
var a = require("./a"); // <------ this is the only necessary change
The solution is to 'forward declare' your exports object before requiring any other controller. So if you structure all your modules like this and you won't run into any issues like that:
// Module exports forward declaration:
module.exports = {
};
// Controllers:
var other_module = require('./other_module');
// Functions:
var foo = function () {
};
// Module exports injects:
module.exports.foo = foo;
What about lazy requiring only when you need to? So your b.js looks as follows
var ClassB = function() {
}
ClassB.prototype.doSomethingLater() {
var a = require("./a"); //a.js has finished by now
util.log(a.property);
}
module.exports = ClassB;
Of course it is good practice to put all require statements on top of the file. But there are occasions, where I forgive myself for picking something out of an otherwise unrelated module. Call it a hack, but sometimes this is better than introducing a further dependency, or adding an extra module or adding new structures (EventEmitter, etc)
You can solve this easily: just export your data before you require anything else in modules where you use module.exports:
classA.js
class ClassA {
constructor(){
ClassB.someMethod();
ClassB.anotherMethod();
};
static someMethod () {
console.log( 'Class A Doing someMethod' );
};
static anotherMethod () {
console.log( 'Class A Doing anotherMethod' );
};
};
module.exports = ClassA;
var ClassB = require( "./classB.js" );
let classX = new ClassA();
classB.js
class ClassB {
constructor(){
ClassA.someMethod();
ClassA.anotherMethod();
};
static someMethod () {
console.log( 'Class B Doing someMethod' );
};
static anotherMethod () {
console.log( 'Class A Doing anotherMethod' );
};
};
module.exports = ClassB;
var ClassA = require( "./classA.js" );
let classX = new ClassB();
A solution which require minimal change is extending module.exports instead of overriding it.
a.js - app entry point and module which use method do from b.js*
_ = require('underscore'); //underscore provides extend() for shallow extend
b = require('./b'); //module `a` uses module `b`
_.extend(module.exports, {
do: function () {
console.log('doing a');
}
});
b.do();//call `b.do()` which in turn will circularly call `a.do()`
b.js - module which use method do from a.js
_ = require('underscore');
a = require('./a');
_.extend(module.exports, {
do: function(){
console.log('doing b');
a.do();//Call `b.do()` from `a.do()` when `a` just initalized
}
})
It will work and produce:
doing b
doing a
While this code will not work:
a.js
b = require('./b');
module.exports = {
do: function () {
console.log('doing a');
}
};
b.do();
b.js
a = require('./a');
module.exports = {
do: function () {
console.log('doing b');
}
};
a.do();
Output:
node a.js
b.js:7
a.do();
^
TypeError: a.do is not a function
The important thing is not to re-assign the module.exports object that you have been given, because that object may have already been given to other modules in the cycle! Just assign properties inside module.exports and other modules will see them appear.
So a simple solution is:
module.exports.firstMember = ___;
module.exports.secondMember = ___;
The only real downside is the need to repeat module.exports. many times.
Similar to lanzz and setec's answers, I have been using the following pattern, which feels more declarative:
module.exports = Object.assign(module.exports, {
firstMember: ___,
secondMember: ___,
});
The Object.assign() copies the members into the exports object that has already been given to other modules.
The = assignment is logically redundant, since it is just setting module.exports to itself, but I am using it because it helps my IDE (WebStorm) to recognise that firstMember is a property of this module, so "Go To -> Declaration" (Cmd-B) and other tooling will work from other files.
This pattern is not very pretty, so I only use it when a cyclic dependency issue needs to be resolved.
It is fairly well suited to the reveal pattern, because you can easily add and remove exports from the object, especially when using ES6's property shorthand.
Object.assign(module.exports, {
firstMember,
//secondMember,
});
the extremely simple solution is often:
usually you'd have the require at the top of the file ...
var script = require('./script')
function stuff() {
script.farfunction()
}
instead, just require it "in the function"
function stuff() {
var _script = require('./script')
_script.farfunction()
}
An other method I've seen people do is exporting at the first line and saving it as a local variable like this:
let self = module.exports = {};
const a = require('./a');
// Exporting the necessary functions
self.func = function() { ... }
I tend to use this method, do you know about any downsides of it?
TL;DR
Just use exports.someMember = someMember instead of module.exports = { // new object }.
Extended Answer
After reading lanzz's response I could finally figure it out what is happening here, so I'll give my two cents on the subject, extending his answer.
Let's see this example:
a.js
console.log("a starting");
console.log("a requires b");
const b = require("./b");
console.log("a gets b =", b);
function functionA() {
console.log("function a");
}
console.log("a done");
exports.functionA = functionA;
b.js
console.log("b starting");
console.log("b requires a");
const a = require("./a");
console.log("b gets a =", a);
function functionB() {
console.log("On b, a =", a)
}
console.log("b done");
exports.functionB = functionB;
main.js
const a = require("./a");
const b = require("./b");
b.functionB()
Output
a starting
a requires b
b starting
b requires a
b gets a = {}
b done
a gets b = { functionB: [Function: functionB] }
a done
On b, a = { functionA: [Function: functionA] }
Here we can see that at first b receives an empty object as a, and then once a is fully loaded, that reference is updated through exports.functionA = functionA. If you instead replace the entire module with another object, through module.exports, then b will lose the reference from a, since it will point out to the same empty object from the beginning, instead of pointing to the new one.
So if you export a like this: module.exports = { functionA: functionA }, then the output will be:
a starting
a requires b
b starting
b requires a
b gets a = {}
b done
a gets b = { functionB: [Function: functionB] }
a done
On b, a = {} // same empty object
Actually I ended up requiring my dependency with
var a = null;
process.nextTick(()=>a=require("./a")); //Circular reference!
not pretty, but it works. It is more understandable and honest than changing b.js (for example only augmenting modules.export), which otherwise is perfect as is.
Here is a quick workaround that I've found use full.
On file 'a.js'
let B;
class A{
constructor(){
process.nextTick(()=>{
B = require('./b')
})
}
}
module.exports = new A();
On the file 'b.js' write the following
let A;
class B{
constructor(){
process.nextTick(()=>{
A = require('./a')
})
}
}
module.exports = new B();
This way on the next iteration of the event loop classes will be defined correctly and those require statements will work as expected.
One way to avoid it is to don't require one file in other just pass it as an argument to a function what ever you need in an another file.
By this way circular dependency will never arise.
If you just can't eliminate circular dependencies (e.g useraccount <---> userlogin), there's one more option...
Its as simple as using setTimeout()
//useraccount.js
let UserLogin = {};
setTimeout(()=>UserLogin=require('./userlogin.js'), 10);
class UserAccount{
getLogin(){
return new UserLogin(this.email);
}
}
//userlogin.js
let UserAccount ={};
setTimeout(()=>UserAccount=require('./useraccount.js'), 15);
class UserLogin{
getUser(){
return new User(this.token);
}
}

Testing node js module with injected dependecy

I am java, c# programmer with more than 10 years experience. Now I have to write some code in js and really, I feel like Alice in Wonderland....
I have myModule.js :
module.exports = function (logger) {
return {
read: function (param) {
......
logger.eror(....)
},
write: function (param) {
......
logger.info(....)
}
};
}
The logger.js, (legacy code, I cannot change it) looks similar:
module.exports = function(some_settings){
return {
info: function () {
......
},
error: function () {
......
}
};
}
Important thing: logger is not included to myModule by require("logger") but injected in some "global" index.js file which looks like:
var settings = require("../someSettings.js")();
var logger = require("../logger.js")(settings);
var myModule = require("../myModule .js")(logger);
Now I want to write UT for myModule in mocha. So I want to mock logger. And I face the wall.
I tried proxyquire but this is not good solutions because logger is not included to myModule by require.
I tried sinon stub and mock e.g.:
var logger = require("logger.js");
var loggerMock = sinon.mock(logger);
var myModule= require("myModule.js")(loggerMock);
Or:
var logger = require("logger.js");
var loggerStub = sinon.stub(logger, "info", function() {return ....});
var myModule= require("myModule.js")(loggerStub);
But I still have some errors like :
"Attempted to wrap undefined property error as function"...
Please, be my white rabbit in this javascript freeky world...
When you are testing your module, you can use a fake object for your logger object, i.e.:
const logger = {info: noop, error: noop, debug:...};
function noop() {}
or well create a mock object with sinonjs if you prefer create it programatically and use spy features.
Then, you can inject it wrapping your module definition in a closure (as you posted):
# myModule.js:
module.exports = (dep1, dep2, ...) => {
// module definition
}
Or use rewire package, to "inject" module scoped dependencies (it works only for local-vars, and not need to create a closure in your module):
# myModuleTest
myModule = rewire('./myModule');
myModule.__set__('logger', { /* fake logger */ });

Access to object in module

Im doing some logic which parse json data to object and I want to expose in some module specific object outside that other module can use,
I try with the following which doesnt work,any other idea?
var jsonObject;
module.exports = {
parse: function () {
//here I do the parsing
....
jsonObject = JSON.parse(res)
,
//here I want to expose it outside
jsonObj:jsonObject
}
If you are trying to expose the entire object, you build it like you would any other JavaScript object and then use module.exports at the end :
MyObj = function(){
this.somevar = 1234;
this.subfunction1 = function(){};
}
module.exports = MyObj;
If you just want to expose certain functions, you don't NEED to build it like an object, and then you can export the individual functions :
var somevar = 1234;
subfunction1 = function(){};
nonExposedFunction = function(){};
module.exports = {
subfunction1:subfunction1,
somevar:somevar
};
you simply assign the result of JSON.parse to this.jsonObj:
module.exports = {
parse: function (res) {
this.jsonObj = JSON.parse(res);
}
};
Using this.jsonObj you are exposing the JSON object to the outside and you can use your module in this way:
var parser = require('./parser.js'),
jsonString = // You JSON string to parse...
parser.parse(jsonString);
console.log(parser.jsonObj);

TypeError: Object is not a function at Object.<anonymous> when constructing Javascript w/ new

I've put together a little code in one file, which is below:
var exports = Symphonize;
function Symphonize(generation_specification) {
this.generate_spec = function(){
return generation_specification;
}
}
When I start another JavaScript file in the same project and require the code like so:
var symphonize = require('../bin/symphonize');
var Symp = new symphonize({"test":"test1"});
It throws the error:
/Users/adron/Codez/symphonize/tests/symphonize.js:8
var Symp = new symphonize({"test":"test1"});
^ TypeError: object is not a function at Object.<anonymous>
Is there another way I should be constructing this? I just want the "symphonize" code to require a simple object (an object of configuration that will be JSON) before any functions on that code are called.
When setting the exports something you must do module.exports = Something. You should do something like :
module.exports = Symphonize;
If you had Symphonize as a property on the exports module.exports is not needed
exports.Symphonize = Symphonize;
Use it in a file.
var Symphonize = require('../bin/symphonize').Symphonize
Also var exports is kind of ambiguous statement in Node.

NodeJS module initialization

I have an npm module that I would like to configure once and call in multiple places.
The npm module (let's call it 'signature') is basically like this
module.exports = function(options) {
return new Signature(options);
};
var Signature = function(options) { }
Signature.prototype.sign = function() {}
I made another module ('signer') to configure it:
var signature = require('signature');
module.exports = function() {
// I pass whatever config options here
return signature({});
};
In my code I do:
var signer = require('../utils/signer');
signer.sign();
However this gives me a "has no method "sign" error. What am I doing wrong? I suspect I have to initialize something but not sure what. If I bypass the config module (signer) and just call the signature module then it works fine:
var signature = require('signature');
var s = signature();
s.sign();
Signer exports a function that returns a signature. Try:
var signer = require('../utils/signer');
signer().sign();

Categories