Categories
JavaScript Answers

How to share variables between files in Node.js?

Spread the love

Sometimes, we want to share variables between files in Node.js.

In this article, we’ll look at how to share variables between files in Node.js.

How to share variables between files in Node.js?

To share variables between files in Node.js, we can put our shared variables in a module.

For instance, we write

module.js

const name = "foobar";

exports.name = name;

to export the name variable in module.js by assigning it to exports.name.

And then in main.js, we write

main.js

const myModule = require('./module');

const name = myModule.name;

to call require to include the module.js module and assign the exported contents to myModule.

And then we get the exports.name value with myModule.name,

Conclusion

To share variables between files in Node.js, we can put our shared variables in a module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *