Emad joha
Emad joha

Reputation: 97

how to share variable between more than One file in nodejs

// app.js

var myvar = 1  
module.exports = {myvar}; 

// another in my project

var mynewvar =require("../app.js")
console.log(mynewvar.myvar); // undefined ? 

I need to make var is global in all project ? I'm try global but the same issue can any one help me?

Upvotes: 0

Views: 2197

Answers (2)

Jim B.
Jim B.

Reputation: 4704

My only guess is you might not have the path to app.js right. This works:

// app.js

var myvar = 1  
module.exports = {myvar}; 

// index.js

var mynewvar =require("./app.js")
console.log(mynewvar.myvar);

Here's a repl.it that shows it works:

https://repl.it/repls/CruelMonstrousArchives

Maybe you're doing something different than this?

Upvotes: 1

Theo Itzaris
Theo Itzaris

Reputation: 4681

you can easily achieve this, either in es6(lib.js) way or es5(lib2.js) way.

live example: https://codesandbox.io/embed/mo8z2ooovj

export module es6 lib.js :

const myvar = 1;
export default myvar;`

export module es5 lib2.js :

var myvar2 = 2;
module.exports = myvar2;`

into another file you can import the modules and display the values like so, i use a component:

 import myvar from "./lib";
 import myvar2 from "./lib2";

 // you can use the imported values here as you need


 // e.g.
 function App() {
   return (
     <div className="App">
       <h1>Hello CodeSandbox</h1>
       <p>value from lib.js {myvar}</p>
       <p>value from lib2.js {myvar2}</p>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);`

Upvotes: 1

Related Questions