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 export the variables and then import them where we want to use them.

For instance, we write

module.js

const name = "foobar";

exports.name = name;

to export the name variable with

exports.name = name;

Then we import module.js and use name in main.js with

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

const name = myModule.name;

Conclusion

To share variables between files in Node.js, we export the variables and then import them where we want to use them.

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 *