How to access global variables from required() file in Node? - javascript

Let's say I have 2 files: main.js, and module.js:
//main.js
const myModule = require('./module');
let A = 'a';
myModule.log();
//module.js
module.exports = {
log() {
console.log(A);
}
}
When calling myModule.log, A is not defined. Is there any way I can make global vars from main.js available in module.js? Thanks.

Use force, use global
const myModule = require('./module');
let A = 'a';
global.A = A
myModule.log();

A is not a global variable. every module is itself wrapped in a function, A is local to that function. You need to explicitly pass reference to your variable
module.exports = {
log(a) {
console.log(a);
}
}
//...
//main.js
const myModule = require('./module');
let A = 'a';
myModule.log(A);

Related

Imported module function in app.js does not have access to class instantiation or app.js variables. Javascript node

I have working code that fails when I try to split it into modules, this is a super simplified version to highlight the behavior I don't understand.
When app.js runs, there is a 'ReferenceError: elf1 is not defined'. I do not understand why func1 does not have access to elf1. I thought maybe changing the func1 to an arrow function away from a standard function would make func1 lexically scoped to app.js.
I realize that in App.js I can declare global.elf1 = new Elf() and then func1.js will have access. However, I don't understand why when an arrow function in a module is invoked within the app.js environment it doesn't have access to the app.js variable environment.
I'm sure this is simple and I'm overlooking some obvious behavior, I thought func1 being an arrow function would have access to app.js environment variables since it was invoked in app.js.
//App.js
let Elf = require('./class');
let func1 = require('./func');
var elf1 = new Elf('jim');
func1();
---------------------------------------
//class.js
class Elf{
constructor(name){
this.name = name;
}
shout(){
console.log(`my name is ${this.name}`);
}
}
module.exports = Elf;
----------------------------------
//func.js
let func1 = ()=>{
elf1.shout()
}
module.exports = func1;
func.js has no idea what elf1 is because it's outside of the module scope.
I would just pass in elf1 as a parameter into the func1 function.
//App.js
let Elf = require('./class');
let func1 = require('./func');
var elf1 = new Elf('jim');
func1(elf1);
//func.js
let func1 = (elf1)=>{
elf1.shout()
}
module.exports = func1;

Module functions appear undefined in outside scripts

This code tells me that the parse function is not a function:
const MyModule = require('./MyModule.js');
MyModule.parse('...');
In my module script it's defined like this:
MyModule = {};
MyModule.parse = function(data){
};
module.exports.MyModule = MyModule;
What am I doing wrong?
You have to understand that you are not exporting MyModule but an object (module.exports to be exact) with a member called MyModule (this is what you assigned to it).
If, in your code that requires MyModule, you console.log the result of your require, it will look like:
{ MyModule: {parse: [Function] } }
which is the module.exports object with a property (object) called MyModule that has a property (function) called parse.
So when you require you are getting the module.exports object that you assigned MyModule to and not just MyModule.
If you were to change your module.exports code to:
module.exports.X = MyModule;
Your code that required MyModule would then log:
{ X: {parse: [Function] } }
and you would call it as
MyModule.X.parse(...).
If you then changed your code to read
const MyFabulousModule = require('./MyModule');
you would then call it like:
MyFabulousModule.X.parse(...);
Finally, if you added another line to your module:
module.exports.Y = 4;
And then in your calling code added:
console.log(MyFabulouseModule.Y);
you would see the value 4 logged to the console.
Code:
MyModule.js
const MyModule = {};
MyModule.parse = function(data) {
console.log(data);
};
module.exports.X = MyModule;
module.exports.Y = 4;
test.js
const MyModule = require("./MyModule");
console.log(MyModule);
MyModule.X.parse("hello world");
console.log(MyModule.Y);
To run: node test.js
First of all, you need to add a keyword in definition object.
const MyModule = {};
And you export the object, which you appoint to constant, so you need to call the object from it like this:
MyModule.MyModule.parse('...')

Nodejs Cyclic Dependency with Revealing Module Pattern

I've been running into this issue lately and am looking for a good solution.
Below is the basic setup.
In c.js, a is an empty object. Currently I got around this by putting the var a=require('./a.js') inside the function (cFunction) that needs access to module a's methods. But is that the best way to go about this?
Thanks,
David
main.js
var a = require('./a.js');
a.js
module.exports = (function() {
var b = require('./b.js');
function aFunction() {
console.log("aFunction");
}
return {
aFunction: aFunction
};
})();
b.js
module.exports = (function(){
var c = require('./c.js');
function bFunction(){
console.log('bFunction');
}
return {
bFunction: bFunction
};
})();
c.js
module.exports = (function(){
var a = require('./a.js');
console.log(a); //empty object
function cFunction(){
a.aFunction(); //undefined
console.log('cFunction');
}
return {
cFunction: cFunction
};
})();

How to use internal namespace in javascript moduler pattern

i have 2 .js utility files. and im using module pattern like below. MODULE1 & MODULE2 are global namespaces. In addition internally both the .js files are using same variable name for namespace i.e "mynamespace"
i would like to know that would cause any issue having internal namespace name same in both the modules.
1.js
var MODULE1 = (function () {
var mynamespace = {};
privateVariable = 1;
function privateMethod() {
// ...
}
mynamespace .Init = function () {
// ...
};
return mynamespace ;
}());
2.js
var MODULE2 = (function () {
var mynamespace = {};
privateVariable = 1;
function privateMethod() {
// ...
}
mynamespace.Init = function () {
// ...
};
return mynamespace;
}());
No because mynamesapce variable is only defined in the local scope of each function.
It would cause you trouble if mynamespace was global, which isn't the case

Where are functions and variables exported in Node.js module.exports?

One technique to solve cyclical references issues between modules in Node.js is to export an object before requiring other modules.
For example:
var MyModule = {};
module.exports = MyModule;
var req1 = require("req1.js");
var req2 = require("req2.js");
...
module.exports.MyFunction = function(...) { ... };
module.exports.MyVariable = 22;
...
Where are MyFunction and MyVariable stored? Is it in the MyModule object?
The reason I am asking this question is I want to know whether I can simplify my code. Could I safely replace my code with the following?
var MyModule = {};
module.exports = MyModule;
var req1 = require("req1.js");
var req2 = require("req2.js");
...
MyModule.MyFunction = function(...) { ... };
MyModule.MyVariable = 22;
...
Yes, those two code snippets are functionally equivalent.

Categories