How do I declare an array from a function globally? - javascript

I am trying to declare an array from the function globally so that my other functions can use it as well but I have no idea how to since I am using a csvtojson for converter which makes the whole thing very long and was wondering if this is the way to declare or no?
JS:
//require the csvtojson converter class
var Converter = require("csvtojson").Converter;
// create a new converter object
var converter = new Converter({});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';
// call the fromFile function which takes in the path to your
// csv file as well as a callback function
var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-
Management-New_2017.csv",function(err, result, callback){
if(err){
console.log("An Error Has Occured");
console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
if(err) throw err;
console.log('ohhhhh');
return callback(null, doc);
}
});
var array=[JSarray(function(err,doc)] This is how I declare the array.
My array is doc and so I can return callback but how should I get the array considering I have converter.fromFile("./NTA-SAM-Inventory-List-Security-
Management-New_2017.csv" which is too long so do I omit it when declaring the array or am I doing it wrong ? Thanks.
Update
Just wanted to clarify if I did it correctly.
var JSarray = converter.fromFile("./NTA-SAM-Inventory-List-Security-M
anagement-New_2017.csv",function(err, result, callback){
// if an error has occured then handle it
if(err){
console.log("An Error Has Occured");
console.log(err);
}
// the result of the conversion
console.log(result);
result.toArray(function(err,doc){
if(err) throw err;
console.log('ohhhhh');
return callback(null, doc);
var myArray= doc;
GLOBAL.GlobalMyArray = myArray;
});
});
Is this correct following your answer in declaring it globally?

global variables are not considered good programming practice.
Though you can create a global object module and reference this modules in all other modules in your project and play with exposed properties from it.
A simple example to achieve this is as following in node.js:
Create module GlobalArray. This module will expose a singleton object of the class it defines. The constructor of this class creates member variable. This class now expose the member variable using methods such as Add, Get. The instance of this class is exported from the module.
// File: GlobalArray.js
class GlobalArray {
constructor(){
this.array = [];
}
Add(item) {
this.array.push(item);
}
Get(){
return this.array;
}
}
let globalArray = new GlobalArray();
module.exports = globalArray;
Module for the class which add data to Global Array can be created as following:
// File: Add.js
const globalArray = require("./GlobalArray");
class Add {
AddToGlobalArray(){
globalArray.Add("1");
globalArray.Add("2");
globalArray.Add("3");
globalArray.Add("4");
globalArray.Add("5");
}
}
module.exports = Add;
Module for the class which print data from Global Array can be created as following:
// File: Print.js
const globalArray = require("./GlobalArray");
class Print {
PrintGlobalArray(){
let array = globalArray.Get();
for(let i=0; i<array.length; i++){
console.log(array[i] + "\n");
}
}
}
module.exports = Print;
Both Add and Print modules used statement const globalArray = require("./GlobalArray") to reference the Global Array.
Now, we can use Add and Print modules by referencing them in index.js to add and print data respectively using the Global Array.
// File: index.js
const Add = require("./Add");
const Print = require("./Print");
// Creating object of Add module to add data to global array
let addObject = new Add();
addObject.AddToGlobalArray();
// Creating object of Print module to print data from global array
let printObject = new Print();
printObject.PrintGlobalArray();
After executing index.js, it renders the following output:
>node index.js
1
2
3
4
5

You can set an array global inside of a function by assigning it to the window object.
function myFunction() {
var myArray = new Array();
window.GlobalMyArray = myArray;
}
Once it is set you can use GlobalMyArray from anywhere.
Using Node.Js you can use global
function myFunction() {
var myArray = new Array();
GLOBAL.GlobalMyArray = myArray;
}
You can now access the array globally using GLOBAL.GlobalMyArray
In which case it is very useful to do:
GLOBAL.window = GLOBAL
Like in the web browser.

Related

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){
...

Trouble passing Vector Array through JS classes

I am experiencing trouble passing and array of Vectors (subNodes) held in a class "Node". To class Main. Any blatant mistakes?
// Node class
// other class code
var subNodePos =[]; // array has been correctly populated in node class
// init array in construct
// array has been correctly populated in node class
Node.prototype.getSubNodeArray = function () { return this.subNodePos; }
// Main class
function draw()
{
// code ...
// can access all object variables and methods except for this one array
var famPos = node.getSubNodeArray(); // passing array // fails here 'undefined'
var temp = famPos[0]; // error
}
You have declared subNodePos as a private variable of your node constructor.
But this variable is not available to this method:
Node.prototype.getSubNodeArray = function () { return this.subNodePos; }
You can fix it in at least 2 ways:
Solution 1. Make subNodePos a public member
Make it a property of this in your constructor:
function Node() {
...
this.subNodePos = [];
...
}
Node.prototype.getSubNodeArray = function () { return this.subNodePos; }
Solution 2. Define getSubNodeArray at object level
This is when you want to keep subNodePos private. Then you can keep the var declaration, but must reference it without this:
function Node() {
...
var subNodePos = [];
...
this.getSubNodeArray = function () { return subNodePos; }
...
}

How to export a variable from a module in JavaScript?

According to this post we know that variables can be exported from one module in JavaScript:
// module.js
(function(handler) {
var MSG = {};
handler.init = init;
handler.MSG = MSG;
function init() {
// do initialization on MSG here
MSG = ...
}
})(module.exports);
// app.js
require('controller');
require('module').init();
// controller.js
net = require('module');
console.log(net.MSG); // output: empty object {}
Those above codes are in Node.js and I get one empty object in my controller.js. Could you please help me figure out the reason of this?
Update1
I have updated the above codes:
// module.js
(function(handler) {
// MSG is local global variable, it can be used other functions
var MSG = {};
handler.init = init;
handler.MSG = MSG;
function init(config) {
// do initialization on MSG through config here
MSG = new NEWOBJ(config);
console.log('init is invoking...');
}
})(module.exports);
// app.js
require('./module').init();
require('./controller');
// controller.js
net = require('./module');
net.init();
console.log(net.MSG); // output: still empty object {}
Output: still empty object. Why?
When you console.log(net.MSG) in controller.js, you have not yet called init(). That only comes later in app.js.
If you init() in controller.js it should work.
Another issue i discovered through testing.
When you do MSG = {t: 12}; in init(), you overwrite MSG with a new object, but that doesn't affect handler.MSG's reference. You need to either set handler.MSG directly, or modify MSG: MSG.t = 12;.

node.js instantiate class multiple times

I have a class file that creates socket connections based on the parameter passed in during instantiate.
When I try to instantiate this file multiple times (for loop) it looks like the node.js is handling it like singleton.
Is there a way I can create new instances from a same js file that can hold its own arguments passed?
app.js
for(var i....){
require('./controller/sockets')(param[i]);
}
./controller/sockets
var util = require('util');
var param
Socket = function(iParam) {
param = iParam;
};
util.inherits(Socket,EventEmitter);
Socket.prototype.test = function(){
return param;
};
module.exports = Socket;
Thank you!
Your constructor doesn't actually create anything. All it does it store an argument in a variable. So, when you call it N times, that's all it does is store a different value into the same variable N times in a row.
Your code is essentially doing this:
var param;
var Socket = function(iParam) {
param = iParam;
}
for(var i....){
Socket(param[i]);
}
It is not clear to me what you want it to do, but perhaps the constructor needs to create an object (probably using new), initialize it and then return it.
If you want a new Socket object back from each call to the constructor, then you can do it like this:
var util = require('util');
function Socket(iParam) {
this.param = iParam;
}
util.inherits(Socket,EventEmitter);
Socket.prototype.test = function(){
return this.param;
};
module.exports = function(x) {
return new Socket(x);
};

Categories

Resources