Dynamically updating exports Nodejs - javascript

I have this object that is being exported and imported by other files. Initially, the object is empty but during an event change ( a button clicked), the object is filled with keys and values but still remains empty in the files that imported it. How can I dynamically update an object and then export it with it's new values.
The code looks something like this:
firstFile.js
const anObject = {};
function clicked() {
anObject.firstName = "John";
anObject.lastName = "Doe" ;
}
module.exports = anObject;
secondFile.js
const importedObject = require("./firstFile");
console.log(importedObject) // always returns an empty object

You have to export and call the clicked function. Otherwise you are never actually updating that object.
For example.
firstFile.js
const anObject = {};
function clicked() {
anObject.firstName = "John";
anObject.lastName = "Doe" ;
}
module.exports = anObject;
module.exports.clicked = clicked;
secondFile.js
const importedObject = require("./firstFile");
console.log(importedObject.firstName) //undefined
importedObject.clicked()
console.log(importedObject.firstName) //John
Edit
After discussing further with the OP this is an Electron application. The code above works in Node.js. Electron might have a different setup and require extra steps to make this work.

Related

Nested Function from another file does not access variable inside a function

I want to access local variables from a function inside a file using a nested function imported from another file, but when I try to access it, it displays undefined instead.
File 1:
import { getFirstName } from './getfirstname'
let name = { "fullname" : "John Doe" }
export class Class1 extends React.Component {
getName = (x) => {
var y = x.fullname
getFirstName(y)
}
}
getName(name);
File 2 (getfirstname.js) :
export const getFirstName = (z) => {
var fname = z.split(/\|/).map(s => s .split (/\s+/) [0])
console.log(fname)
}
How can I make sure using getName(name) returns John instead of undefined?
Edit: this working example should be more relevant to the question: https://codepen.io/marwann/pen/VwvRWrr
There are several problems with your code as posted:
Your Class1 extends React.Component for no apparent reason
You define getName as a instance method of Class1 but then try to call it directly, instead of as a property on an instance of Class1
You speak of "returning" but none of your code here returns anything-- it only logs to the console.
Ultimately, I don't think your issue is at all related to importing, and I suspect it is throwing an error when you try to call getName which does not exist in scope.
If we rewrite it with those things fixed, we should be able log a result:
const getFirstName = (z) => {
var fname = z.split(/\|/).map(s => s .split (/\s+/) [0])
return fname
}
let name = { "fullname" : "John Doe" }
class Class1 {
getName = (x) => {
var y = x.fullname;
return getFirstName(y);
}
}
const instance = new Class1();
const fname = instance.getName(name);
console.log(fname);
Note that I've created an instance of your class and called getName from that instance. I've additionally updated both getName and getFirstName to actually return a value.
A few other items to consider:
Nothing about your class as currently exists leverages the benefits you get from organizing your code into a class. It might be worth considering whether or not it is actually necessary.
I would recommend against mixing var with let and const. If you are working in an environment that allows you to leverage let/const, you can just replace any var with a let if it must be reassigned and a const if it will never be reassigned.

how to use a global variable when it takes a value in another file

I have a file called app.js:
let id = 0;
const Func = require('./func.js');
Func.myFunc();
console.log(id);
module.exports = {
id
};
Also I have another file called func.js:
const App = require('./app.js');
var myFunc = () => {
App.id = 100;
}
module.exports = {
myFunc
};
But console.log(id) returns: 0
What you are doing is termed circular dependencies. It is generally frowned upon and there is no allowed instance where this may be required. You're better off creating a third file that will use both of them...
Read this to have a better understanding:
https://nodejs.org/api/modules.html#modules_cycles
How to deal with cyclic dependencies in Node.js
Add another log like:
// app.js ...
console.log(module.exports);
module.exports = { id };
console.log(id);
to see that your code does work somehow, in the way that module.exports has an id property set, but you override that afterwards. Also the property of the export object has nothing todo with the id variable (well, the later gets copied into the first) so console.log will never log 100.
There are two problems with your piece of code:
the circular dependency
module.exports.id is not the same object as the variable id in app.js
In order to solve the first problem, you should create a third file where the variable will be declared and other modules will use that.
Now, to illustrate the second problem, look at the following.
// testModule.js
let variable = 0;
function get_variable() {
return variable;
}
module.exports = {variable, get_variable};
// app.js
const testModule = require('./testModule.js');
testModule.variable = 1234;
console.log(testModule.variable); // will print '1234'
console.log(testModule.get_variable()); // will print '0'
This little misunderstanding of modules, could lead to subtle nasty bugs. I consider that the best practice to solve this would be not to export the 'variable' property directly, but having getter/setter functions in the module, almost like transforming it into a class-like thing.
// testModule.js
let variable = 0;
function get_variable() {
return variable;
}
function set_variable(value) {
variable = value;
}
module.exports = {get_variable, set_variable};

Node.js use variable from module

I have app.js
var List = {};
var Entity = require('./entity.js');
var main = new Entity(); // should be changed List
console.log(List) // still empty
and entity.js
class Entity {
constructor(){
this.id = Math.random();
List[this.id] = this; // List == undefined
}
}
module.exports = Entity;
How can I use List as global variable?
Just import List in entity.js:
At the end of app.js:
module.exports = List;
At the start of entity.js:
const List = require('./app.js');
If your app.js needs to export something else as well, then export an object with a List property instead:
At the end of app.js:
module.exports.List = List;
At the start of entity.js:
const List = require('./app.js').List;
You could also consider putting List into its own module that both app.js and entity.js import.
Don't make List a global variable, if at all possible - work with the module system instead, explicit dependencies without global pollution is one of a module system's big advantages.
You need to pass List param and access in constructor ...
new Entity(List);
constructor(List){
...

How does this module know about the data in another module?

My understanding of modules is that they are distinct from each other. However I don't understand why this code works then.
Lets say I have three files in the node.js framework. One "app.js" driver file and two modules:
Module "one.js" simply has a property called "name":
module.exports = {
name: null
}
Module "two.js" loads module "one.js" and declares a function that prints out the contents of the property "name" in the "one.js" module:
var one = require('./one');
module.exports = {
printname: function()
{
console.log(one.name);
}
}
Now the driver (app.js) imports both modules, sets the property of the first module, then calls the name printing function of the second:
var one = require("./one");
var two = require("./two");
two.printname();
one.name = "John";
two.printname();
When I run this, it prints "null" (fine, it should be empty), then "John" (not fine). How is the second module learning of the value in the first module?
My thought process is: when "two.js" loads its own version of "one.js", the property "name" should always be null. Why is this not the case?
Because you are modifying a property of an Object, and Objects are passed by reference, therefore all the instances that imported one.js got the same instance.
If you need different instances you should export a class and create an instance on demand.
Something like that:
//one.js
class Data {
constructor(data) {
this.data = data;
}
}
export.module = Data;
//two.js
const Data = require('./one');
const data = new Data('John');
one's export is a static object. It it not new every time.
You can change it like so:
module.exports = function() {
return { name: null }
}
Then:
var one = require("./one");
var willAlwaysBeNew = one();
willAlwaysBeNew.name = "john"
var willAlwaysBeNewToo = one();
console.log(willAlwaysBeNew.name) // john
console.log(willAlwaysBeNewToo.name) // null

I am getting: Cannot call method 'someMethodName' of undefined when trying to access an object in a javascript clas

I am almost new to JavaScript, and I am trying to access an object within a class. This is my class definition in a file called analysis.po.js:
var AnalysisPage = function () {
(some code here)
this.getSpousesCreditBureau = function() {
return {
pdScore: getSpousesCreditBureauElement('pdScore'),
qualification: getSpousesCreditBureauElement('qualification'),
estimatedFee: getSpousesCreditBureauElement('estimatedFee'),
currentDebt: getSpousesCreditBureauElement('currentDebt'),
maxDebt: getSpousesCreditBureauElement('maxDebt'),
arrears: getSpousesCreditBureauElement('arrears'),
segment: getSpousesCreditBureauElement('segment'),
bpGlobalRisk: getSpousesCreditBureauElement('bpGlobalRisk'),
groupGlobalRisk: getSpousesCreditBureauElement('groupGlobalRisk')
};
};
(some other code here)
};
module.exports = new AnalysisPage();
This is the piece of code where I try to get the object getSpousesCreditBerauElement in another file called analysis.spec.js:
var App = require('../app.po.js'),
Util = require('../util.js'),
AnalysisPage = require('./analysis.po.js'),
AnalysisData = require('./analysis.data.js');
(some code here)
var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(analysis.getSpousesCreditBureau());
(some other code here)
The error I am getting is:
Cannot call method 'getSpousesCreditBureau' of undefined
You're not actually exporting AnalysisPage and you're not calling it correctly.
Export the class with:
module.exports = AnalysisPage;
In comparison
module.exports = new AnalysisPage();
Exports an instance of the class.
The right way to call it is then:
var instance = new AnalysisPage();
Util.verifyElementsAreDisplayed(instance.getSpousesCreditBureau());
(Original question has been modified, code was:)
var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(AnalysisPage.getSpousesCreditBureau());
You can export just the instance, in that case call it like:
var instance = require('./analysis.po.js');
Util.verifyElementsAreDisplayed(instance.getSpousesCreditBureau());
So no new anywhere.
Did you tried:
var analysis = new AnalysisPage();
Util.verifyElementsAreDisplayed(analysis.getSpousesCreditBureau());
When you access the method like this AnalysisPage.getSpousesCreditBureau() you are not accessing the instance, but the class definition.

Categories

Resources