how to use a variable only after it is set in nodejs - javascript

I am using a global variable job_name. I will set the value for this variable in file1.ts. I would like to use the global variable in file2.ts. However, in file2.ts, job_name is undefined though I am setting in file1.ts. Seems like since file1 and file2 are loaded as soon as project is initiated (even before job_name is set in file1), file2 is assuming a value of undefined for job_name. Please let me know how I can use job_name in file2.ts with the value set in file1.ts.
global.d.ts
declare global {
var job_name: any
}
export { };
Extra info for reference:
Original question (this is my actual scenario) -
Global variable for 'log' in other files is undefined since it is set after project is started in nodejs

Related

ReferenceError: Cannot access 'prefixfile' before initialization

i searched stackoverflow before asking this, none really solved my issue
I'm writing a discord bot and I'm writing a way to have custom prefixes. So far, I have this for handling situations where the prefix for a guild isn't in the json file.
const prefixfile = require('./prefixes.json');
function writePrefix(guildid) {
const currentprefixes = prefixfile;
currentprefixes[guildid] = "!";
fs.writeFile('./prefixes.json', JSON.stringify(currentprefixes), output => {
console.log(output);
});
delete require.cache[require.resolve(`./prefixes.json`)];
const prefixfile = require('./prefixes.json');
}
I get the error ReferenceError: Cannot access 'prefixfile' before initialization
EDIT: I've fixed that issue and got another:
fs.writeFile('./prefixes.json', JSON.stringify(currentprefixes), output => {
console.log(output);
});
that doesn't write anything to ./prefixes.json, even though currentprefixes has data that should be written.
any ideas?
Even though a variable named prefixfile is declared outside your function, the first line of your function references the variable declared locally with same name - even though it is still not declared at that point. This happens because all the variables of your program are added to their respective lexical scopes at compile time - before any code has a chance to run.
However, since the local variable is declared with const, trying to access it before it has actually been declared will cause the ReferenceError that you see.
See the TDZ (Temporal Dead Zone) notes for further information on this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz
like IAmDranged said, the variable prefixfile was not declared in the function. I fixed that by not using a function and moving it all inside my if statement. My other issue was that fs.writeFile() didn't write anything - I fixed by using fs.writeFileSync().

Foreign variables display as 'undefined'

Hello to anyone who will read this post,
I have two standalone javascript files, one of which possesses a class with variables that I would like to use in the other file. We will call the file that possesses the class script.js, and the other file index.js. The code inside index (which is the main file we want to run) compiles fine, but when I run it, my variable prints out as 'undefined'. The variables work fine when they are inside index file themselves, but inside the script.js's class, they are undefined. I would very much like to keep script.js, and keep my variables inside the class. I use an object instance that we will call script obj, and I would very much like to keep my objects. I am not a fan of the static method.
Example: Script.js's class
class script{
constructor(){
var laggies = parseInt(1)
}
}
Above, laggies is defined with a value of 1. Nice, yes? Now let us look at index.js(Just pretend that the object has been initialized)
Example:
console.log(obj.laggies)
This is where I get my problem. I am using repl.it with node version 12.16.1
Thank you for your time.
You are getting the undefined error because the class does not have a variable called laggies. Its defined inside the constructor of the class and not elsewhere.
Try this
class script{
constructor() {
this.laggies = parseInt( 1)
}
}

How to modify variables from another file in node.js

I'm currently working with the discord.js library.
I guess I can call it by this name, but whenever I want to access a file, this doesn't work.
Let's say I have a file called calc.js and I want to access the main.js file and take a variable out of there using exports and require it to just take the value out of it.
But I haven't found even one way online to modify the variables and return another value to the file.
Can someone help me?
As noted, JavaScript doesn't pass every variable by reference. If you need to access a primitive value like a number, you could declare it as a local variable and export functions to access and modify it. Something like this rough example:
increment.js
let count = 0;
module.exports = {
get: () => count,
increment: () => ++count
};
main.js
const { get, increment } = require('./increment.js');
console.log(get());
console.log(increment());
console.log(get());
Edit: You should probably not name your accessor get, as that's the key word used to describe getters in ES6. Or better yet, turn such a get function into a getter with a more suitable name.

JavaScript Revealing Module pattern private variable state

I have recently started working on a JavaScript project and coming from Java world things seem, not surprisingly, weird at times.
I was implementing a simple module (Using revealing module pattern, afaik) which would provide config based on initialisation but notice that after a "local" variable domain is assigned in init() function its value differs depending whether it is accessed via a "getter" function getDomain() or directly via domain variable as exposed via modules "public" API.
See the following stripped down code which demonstrates the issue.
var ConfigManager = (function() {
var privateDomain = 'default';
function init(dom) {
privateDomain = dom;
}
function getDomain() {
return privateDomain;
}
return {
init: init,
domain: privateDomain,
getDomain: getDomain
};
})();
console.log(ConfigManager.domain); // Prints 'default'
console.log(ConfigManager.getDomain()); // Prints 'default'
ConfigManager.init('new domain');
console.log(ConfigManager.domain); // Prints 'default' <-- What??
console.log(ConfigManager.getDomain()); // Prints 'new domain'
At this point I am very confused how a variable returned from a getter function can have a different value when it is accessed directly?
Than you in advance!
Since privateDomain is a String, you're not copying / returning the reference, but the value.
Therefore when you're changing the domain using the init function, it just updates privateDomain, since domain has no link to it other than being a copy.
Hope it helps! :)
It's because when domain is returned, it's value is still "default". It's how Javascript works, more info here: Javascript by reference vs. by value
But when you use the function "getDomain" you will get the updated value.
Also have a look at the get/set syntax: Getter

Is there Global variables in EXT JS

In java and C++ we could store a variable globally and access its value from any where in the project.
Say, i am inside a class called Residence and i am saving the residenceNumber which is a INT to a global variable called houseNumberGlobalVariable.
Now, i could access houseNumberGlobalVariable from any class in the project. In a similar fashion, is there a Global variable in EXTJS that i could use.
I need to set a value from one class and access it from another. What is the equivalent in EXT JS. I don't think there's a global variable concept in EXTJS, but what is the equivalent in it ?
Create a special class and put all your global variables there.
Ext.define('MyApp.global.Vars', {
singleton: true,
....
houseNumberGlobalVariable: undefined
});
This way if you need access for it anywhere in the code just use MyApp.global.Vars.houseNumberGlobalVariable
Just declare a variable in app.js it will act as global variable.
var globalVar;
You can add anything into that like
globalVar.myStore = yourStore;
Based on your Application you can declare your global variable.
Scenario 1 : Declare inside the config
If you are going to use getter/setter methods (i.e change the variable frequently then go for config based)
Declaring the Appconstants
Ext.define('Practice.utilities.AppConstants', {
alias: 'widget.AppConstants',
config: {
mainVarTest: 'mainVarTest',
},
testvar: 'Testing value',
foo: 'bar',
meh: 42,
constructor: function(options) {
this.initConfig(options);
}
});
Calling the variable
var AppConstants = Ext.widget("AppConstants");
console.log(AppConstants.getMainVarTest());
Scenario 2 : Declare inside Singleton class
If your application needs global variable but it wont be alter any more inside the app. This class help to load the constant variable only once. (i.e you are not going changing the variable). This type is suits for your application
Declaring
Ext.define('Practice.utilities.AppConstants', {
alias: 'widget.AppConstants',
singleton: true,
testvar: 'Testing value',
foo: 'bar',
meh: 42,
});
Calling
var AppConstant=Practice.utilities.AppConstants;
console.log(AppConstant.foo);
Scenario 3 : Declare as Statics
Statics is static variable (exactly same as java). Advantage of using static variable is the life time of variable is indefinite longer period until explicitly cleared.
Ext.define("Practice.utilities.AppConstants", {
statics: {
mainVarTest: 'mainVarTest'
},
});
I noticed the one thing missing here was a solution from the Sencha Architect program on how to create a global variable.
Go to your "Application" node on the project Inspector. Next click in the Configs search/Filter box, this is not only for searching but for creating config entries too. When you first look at this box it will have a Smokey pre-filled text of Filter Configs... .
Enter your global variable name and you will notice nothing is found in the list below, (if the value is found in the config list then you already have this variable or your using a keyword). To the right of the text box and the lock icon is an "Add" button. Click the "Add" button to add your global variable into the application.
So lets say we have created the Foo variable at this point. You will now see an entry in your config list. To the left of this entry is an ellipses button, this is currently designating that the new variable we created is a String. Click the button and change it to something different like a 'Number' field. Enter a value for this new variable and your now done, you have a global variable.
So how do you access this newly created variable? here is a sample bit of code stuffing the global into a local variable to be used.
var bar= MyApp.app.Foo;
The 'MyApp' reference is the Application name config setting for the application you are creating. You can find this same value in the config settings of the Application node by filtering on name.
var globalVar = {}; add in your app.js file, its working fine

Categories

Resources