get all defined variables in current scope - javascript

I'm parsing a website which contains stuff like
hmapId[7]='42500000000626135';
hmapStartInterv[7]='750';
hmapEndInterv[7]='846';
hmapUrlInterv[7]='some url';
hmapNameInterv[7]="some name"
hmapRoleInterv[7]='some role';
My plan is to write that into a .js file and execute it with node js. After that I want to have some lines of code giving me all variables defined before as JSON to use the data in some other program. What's the best way to do this?
Thanks

For the current scope, it's not possible (AFAIK), for the global scope you have the globalobject in node.js (window in navigator embedded js engines), which get the global variables properties:
// on global scope, with x not defined as a "var"
x=25
console.info(global['x']===x) // --> writes down 'true'

Related

Accessing variables and methods from another file

In this case, How do I access the variable and method declared in a file from another file?
File one
jQuery(function(t) {
var myVar = 'myValue',
e = function(t) {
console.log('myLog');
}
});
File two
jQuery(function($){
// ????
});
You don't. It has nothing to do with files (JavaScript largely doesn't care about files unless they're ES2015+ modules), it has to do with the fact that both myVar and e are entirely private to the anonymous function you're passing into jQuery in the first code block. Even other code outside that function in the same file would be unable to access them.
You'd have to change the first file to make that information accessible outside that function. You could do that by making them globals (blech), or by having a single global you use for all of your things like this with an object with properties for these things (slightly less "blech" :-) ), or by using something like Webpack and true modules.
It really depends on how you setup your scripts. For instance:
<script src="fileOne.js"></script>
<script src="fileTwo.js"></script>
Then you will be able to do the following:
File One:
- Declare variable x
File Two:
- Access variable x
I recommend taking a look at this, it'll help with understanding variable scope (however this doesn't cover ES6's let): https://www.w3schools.com/js/js_scope.asp

How do I create a global variable in Geddy

I'm like to define a global variable box that is available in all controllers across my app in Geddy. How would one go about doing this?
You can add a global variable in: /config/secrets.json. If you don't have this secret yet it can be generate using:
geddy gen secret
And then add below to the secret.json.
{
"box": "value of box"
}
And value can be used geddy.config.box

Namespace import in node.js

I've got some function that allows to merge namespace, very similar to import when the module contains lot's of function (I expose an API with dozens of combinators)
It generates lots of var f = target.f; for every item from the export
function getNamespace(name, exports){
var output='';
for(var item in exports){
output += 'var ' + item + ' = '+name+ '.'+item + ';';
}
return output;
}
and usage:
var paco = require('./paco.js');
eval(paco.getNamespace('paco', paco));
// instead of paco.between(paco.start(),paco.content(),paco.end())
between(start(), content(), end())
Question:
I there a way to 'hide' the eval into the some function ? I don't want neither to mutate global namespace nor to call vm.runInThisContext, just need to add some local variables into the calling context after call function similar to require.
I mean I need something like
import('./paco');
// this should work like this
// var paco = require('./paco.js');
// var between = paco.between;
but without mutation of global and without eval in the calling scope.
tl;dr: No.
In order to understand why this is impossible, it's important to understand what Node is doing behind the scenes.
Let's say we define a function in test.js:
function foo() {
var msg = 'Hello world';
console.log(msg);
}
In traditional browser JavaScript, simply putting that function declaration in a file and pulling the file in with a <script> tag would cause foo to be declared in the global scope.
Node does things differently when you require() a file.
First, it determines exactly which file should be loaded based on a somewhat complex set of rules.
Assuming that the file is JS text (not a compiled C++ addon), Node's module loader calls fs.readFileSync to get the contents of the file.
The source text is wrapped in an anonymous function. test.js will end up actually looking like this:
(function (exports, require, module, __filename, __dirname) {
function foo() {
var msg = 'Hello world';
console.log(msg);
}
});
This should look familiar to anyone who has ever wrapped their own code in an anonymous function expression to keep variables from leaking into global scope in a browser. It should also start making sense how "magic" variables in Node work.
The module loader evals1 the source text from step 3 and then invokes the resulting anonymous function, passing in a fresh exports object. (See Module#_compile.)
1 - Really vm.runInThisContext, which is like eval except it does not have access to the caller's scope
After the anonymous wrapper function returns, the value of module.exports is cached internally and then returned by require. (Subsequent calls to require() return the cached value.)
As we can see, Node implements "modules" by simply wrapping a file's source code in an anonymous function. Thus, it is impossible to "import" functions into a module because JavaScript does not provide direct access to the execution context of a function – that is, the collection of a function's local variables.
In other words, there is no way for us to loop over the local variables of a function, nor is there a way for us to create local variables with arbitrary names like we can with properties of an object.
For example, with objects we can do things like:
var obj = { key: 'value' };
for (var k in obj) ...
obj[propertyNameDeterminedAtRuntime] = someValue;
But there is no object representing the local variables of a function, which would be necessary for us to copy the properties of an object (like the exports of a module) into the local scope of a function.
What you've done is generate code inside the current scope using eval. The generated code declares local variables using the var keyword, which is then injected into the scope where eval was called from.
There is no way to move the eval call out of your module because doing so would cause the injected code to be inserted into a different scope. Remember that JavaScript has static scope, so you're only able to access the scopes lexically containing your function.
The other workaround is to use with, but you should avoid with.
with (require('./paco.js')) {
between(start(), content(), end())
}
with should not be used for two reasons:
It absolutely kills performance because V8 cannot perform name lookup optimizations.
It is deprecated, and is forbidden in strict mode.
To be honest, I'd recommend that rather than doing something tricky with eval, do your future maintainers a favor and just follow the standard practice of assigning a module's exports to a local variable.
If you're typing it that often, make it a single-character name (or use a better editor).
According to this answer Global variables for node.js standard modules? there is global object the same as in browser there is window. So you can add key to that object
function getNamespace(exports) {
for(var item in exports){
global[item] = exports[item];
}
}
and use it as:
paco.getNamespace(paco);
no need for eval at all.
No. It's not possible to modify the local scope from an external module. Reason being, when eval is called in the external module, its context will be the external module, not the scope requiring the module.
In addition, vm.runInThisContext does not have access to the local scope, so that wont help you either.

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

Obtain all functions in a file in Node.js

I have some functions inside a file. I'm trying to obtain all functions in that file, from within that file. Normally, all functions are in the window object, but I'm using Node.js, which does not seem to have a window object.
Say I have something along the lines of the following in a file:
function foo() {}
function bar() {}
then:
Are the functions saved in some global object?
If not, how can I access these functions without knowing their names? Can I iterate through all existing functions and obtain them in such a way?
The following is a common pattern
var foo = exports.foo = function() {
// ...
}
This way its written to exports and you can access it locally as foo
You want to get access to the current scope object but it's impossible in JavaScript.
Your functions are wrapped in a closure. Remember, node wraps file modules within something like this
var module = { exports: {}};
(function(module, exports){
// your file module content
})(module, module.exports);
They are locals. Assign functions to an object, exports or global to enumerate them.

Categories

Resources