user3180402
user3180402

Reputation: 599

How to declare and access global variable

What Im doing wrong in the below code?

//File1.js
var arr = [];
function insertName {
    var name = "josh";
    arr.push(name);
    return name;
};
function validName(key) {
var index = arr.indexOf(key);
    if (index == -1) {
        return false;
    } else {
        return true;
    }
}

var result = insertname();
exports.arr = arr;
exports.validName = validName;


//File2.js
var file1 = require("./File1.js");
var name = "josh";
var verify = file1.validName(name);
if(verify) {
cosnole.log("Valid name");
}else {
console.log("Error");
}

node File1.js
node File2.js

When Im executing File2.js, Im gettin undefined for arr[]. Can someone help me what Im doing in the below code

Upvotes: 0

Views: 101

Answers (3)

Ramesh Boddepalli
Ramesh Boddepalli

Reputation: 301

Your code contains mistakes change your code like below

File1.js

  var arr = [];

  function insertName() {
        var name = "josh";
        arr.push(name);
        return name;
  };

  function validName(key) {
      var index = arr.indexOf(key);
      if (index == -1) {
      return false;
    } else {
        return true;
   }
 }

 var result = insertName();
 exports.validName = validName;

File2.js

  var file1 = require("./File1.js");
  var name = "josh";
  var verify = file1.validName(name);

 if(verify) {
    console.log("Valid name");
 } else {
      console.log("Error");
 }

Upvotes: 1

Xeijp
Xeijp

Reputation: 873

You can simply use global.(name) = (value)

Example :

main.js

global.foo = 1;
require('./mod.js').show();

mod.js

module.exports = {
    show : function(){
        console.log(global.foo); // which prints "1"
    }
}

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239653

Node.js modules retain the variables you declared at their top level, till the module is Garbage Collected or you manually delete them. If you look at your File1.js, you are exporting the array object, nothing else. So when you say

var file1 = require("./File1.js");

file1 is just a reference to a JavaScript object which has an arr property. You can check this by printing the file1. The functions you created in File1 are never exported. So, you can fix it like this*

exports = module.exports = {
    validName: validName,
    insertName: insertName
}

Now, you are exporting the functions and they can still access the arr variable. From File2, you can invoke insertName like this

file1.insertName();
if (file1.validName("josh")) {
    console.log("Valid name");
} else {
    console.log("Error");
}

* To know more about exports and module.exports, you can check my blog post about this

Upvotes: 1

Related Questions