I am trying to update the contents of a variable in nodejs with the use of a string.
In client side javascript this was done with the use of window[variable] however since there is no "window" in nodejs. I tried using "this" and "module", however all im getting is an empty object. need help thanks
Code Snippet:
var myVariable = 'Hello';
var exchangeVariable = 'myVariable';
this[exchangeVariable] = 'Hello World';
/*
myVariable should equal to 'Hello World!'
*/
Thanks!
Here's some background before I answer your question directly:
In JavaScript, objects can be either indexed by the dot notation (someObj.property) or by indexing them as you do in your example (someObj["property"])
In the browser, window is the global context that the browser evaluates your code within. Node uses a variable called global.
So, if you want to reference a variable you've defined globally:
> var someGlobalVar = "hi";
> var myLookupKey = "someGlobalVar";
> global[myLookupKey]
'hi'
However, this is generally considered very bad practice (in Node and the browser). There are a myriad of reasons for this, but I'm focusing on just one:
In Node, modules (each required file) should be treated as if they do not share global state (and in some cases, they cannot share state). I encourage you to read through the modules section of the node documentation if you are trying to share state across files.
You could create your own variables hash or array and assign the variable yourself.
var myVariable = "Hello";
var varArray = new Array()
varArray["exchangeVariable"] = myVariable;
Related
Is it possible to programmatically declare a nodejs const from a variable (string?)
let myConsts = ["const1","const2","const3"];
myConsts.forEach(function(label){
defineConst(label,"value"); // I need this function
})
defineConst should define a const, something like the PHP "define" function, but for nodejs
No, you can't really do that in Javascript. For a bit, I thought maybe you could hack it with eval() which is pretty much always the wrong way to solve a programming problem, but even eval() won't introduce a new const variable to the current scope. It will introduce a new var variable to the current scope as in this:
// dynamic variable name
let varName = "test";
// create variable in the current scope
eval("var " + varName + " = 4;");
// see if that variable exists and has the expected value
console.log(test);
But, alas you can't do this with const. You can read more about why here: Define const variable using eval().
Whatever programming problem you are trying to solve can likely be solved in a much better way since you really shouldn't be introducing dynamically named local variables. It's much better to use something like a Map object or a regular object with dynamically named properties in order to keep track of values with dynamic names to them.
If you shared the actual programming problem you're trying to solve (rather than your attempted solution), we could advise further on the best code for that particular problem.
Here's an example of the ability to store dynamically named properties on an object:
let base = {};
// dynamic property name (any string value in this variable)
let varName = "test";
// set property value with dynamic property name
base[varName] = "Hello";
// can reference it either way
console.log(base[varName]);
console.log(base.test);
Or, it can be done using a Map object:
let base = new Map();
// dynamic Map element key (any string value in this variable)
let varName = "test";
// set Map element with dynamic key
base.set(varName, "Hello");
// can reference it either way by the key
console.log(base.get(varName));
console.log(base.get("test"));
I have a list of valid values that I am storing in a data store. This list is about 20 items long now and will likely grow to around 100, maybe more.
I feel there are a variety of reasons it makes sense to store this in a data store rather than just storing in code. I want to be able to maintain the list and its metadata and make it accessible to other services, so it seems like a micro-service data store.
But in code, we want to make sure only values from the list are passed, and they can typically be hardcoded. So we would like to create an enum that can be used in code to ensure that valid values are passed.
I have created a simple node.js that can generate a JS file with the enum right from the data store. This could be regenerated anytime the file changes or maybe on a schedule. But sharing the enum file with any node.js applications that use it would not be trivial.
Has anyone done anything like this? Any reason why this would be a bad approach? Any feedback is welcome.
Piggy-backing off of this answer, which describes a way of creating an "enum" in JavaScript: you can grab the list of constants from your server (via an HTTP call) and then generate the enum in code, without the need for creating and loading a JavaScript source file.
Given that you have loaded your enumConstants from the back-end (here I hard-coded them):
const enumConstants = [
'FIRST',
'SECOND',
'THIRD'
];
const temp = {};
for (const constant of enumConstants) {
temp[constant] = constant;
}
const PlaceEnum = Object.freeze(temp);
console.log(PlaceEnum.FIRST);
// Or, in one line
const PlaceEnum2 = Object.freeze(enumConstants.reduce((o, c) => { o[c] = c; return o; }, {}));
console.log(PlaceEnum2.FIRST);
It is not ideal for code analysis or when using a smart editor, because the object is not explicitly defined and the editor will complain, but it will work.
Another approach is just to use an array and look for its members.
const members = ['first', 'second', 'third'...]
// then test for the members
members.indexOf('first') // 0
members.indexOf('third') // 2
members.indexOf('zero') // -1
members.indexOf('your_variable_to_test') // does it exist in the "enum"?
Any value that is >=0 will be a member of the list. -1 will not be a member. This doesn't "lock" the object like freeze (above) but I find it suffices for most of my similar scenarios.
I want to generate the short id of number type, but when I call shortid method and output id and emaill, the contents of the output in the console are the same as the incoming variable. the gist in github
I get an answer that change 'var self = this ' to 'var self = {}', because 'this' in method equal 'global'.
I am trying to use a string ('npcName') as a variable name. So far I have tried casting dialogMap into a DynamicAccess object, but it gives me the error 'Invalid array access' when I try this:
var npcName:String = 'TestNPC';
var casted = (cast Registry.dialogMap:haxe.DynamicAccess<Dynamic>);
var tempname = casted[root.npcName[0].message];
trace(tempname);
'dialogMap' is an empty map which I want to fill like so:
Registry.dialogMap['message'] = root.npcName[0].message;
How can I use npcName, a string, in the above line of code? Is there a way to transform the string into something usable? Any help would be appreciated.
The haxe.DynamicAccess doesn't have array access (like map[key]), but is an abstract type for working with anonymous structures that are intended to hold collections of objects by the string key. It is designed to work with map.get(key) and map.set(key). It is basically a nicer wrapper around Reflect.field and Reflect.setField and does some safety checks with Reflect.hasField.
var variable = "my_key";
var value = 123;
var dynamicMap = new haxe.DynamicAccess<Dynamic>();
dynamicMap.set(variable, value);
I'm noticing you are doing very much cast and dynamic, so untyped code, which is a bit of contradiction in a typed language. What is the actual type of dialogMap?
Not sure you are aware of it but, Haxe has its own maps, which are fully typed, so you don't need casts.
var map = new Map<String, Int>();
map[variable] = value;
I think this article helps understanding how to work with dynamic (untyped) objects.
Tip; for testing such small functionalities you can doodle around on the try.haxe site : http://try.haxe.org/#4B84E
Hope this helps, otherwise here is some relevant documentation:
http://api.haxe.org/haxe/DynamicAccess.html
https://haxe.org/manual/std-reflection.html
https://haxe.org/manual/types-dynamic.html
http://code.haxe.org/category/beginner/string-variable-reflection.html
I want to know how to use a variable string to reference a movie clip in a hierarchy in AS2.
For example, and please forgive my newbie coding:
If my variable is defined as:
_root.MovieName = "Bob";
Then I'd like to be able to write:
_root.MovieName.ChildClip.gotoAndPlay("Label");
Where MovieName is the string "Bob" and not an actual instance called "MovieName". So Flash looks for an instance of "Bob" and goes into the child clips from there.
Is there any way to do this?
_root actually is a reference to the "root" of the movie, which also inherits a bunch of properties, it behaves like an object, so yes, you can do things like the following:
trace(_root["Bob"]); //Should return the instance.
var movieName = "Bob";
trace(_root[movieName]); //Should be the same.
I FOUND THE ANSWER!
In order to refer to movie clip instances using variables, first declare that variable as a string, then use the this[] handler. Here is the code that worked for me and the page that held it:
// CREATE THE STRING
var newString:String = "movieClipInstanceName";
// ASSUMING YOU ALREADY HAVE A MOVIECLIP WITH AN INSTANCE NAME OF "movieClipInstanceName" ON STAGE,
//CHANGE THE ALPHA OF THE MOVIECLIP TO 0
this[newString].alpha = 0;
And the page:
http://www.kirupa.com/forum/showthread.php?327501-Converting-String-to-Movie-Clip-Instance-Name
Big thanks to everyone who pitched in to help me!