how to get a variable from a file to another file in node.js


Question

Here is my first file:

var self=this;
var config ={
    'confvar':'configval'
};

I want this config variable in another file, so what I have done in another file is:

conf = require('./conf');
    url=conf.config.confvar;

but it gives me an error.

TypeError: Cannot read property 'confvar' of undefined

Please suggest what can i do?

1
39
3/17/2013 4:26:34 AM

Accepted Answer

What you need is module.exports

Exports

An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.

For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:

module.exports = { variableName: "variableValue" };

OR you can set the individual value with:

module.exports.variableName = "variableValue";

To consume that value in another file, you need to require(...) it first (with relative pathing):

var sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);
87
3/9/2018 10:04:16 PM

FileOne.js

module.exports = { ClientIDUnsplash : 'SuperSecretKey' }


FileTwo.js

var {ClientIDUnsplash} = require('./FileOne');

This example works best for ReactJs


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon