While testing some code I came across a situation that I can not explain. After hours of googling I couldn't really figure out the right questions to ask. Any help in the right direction or the correct terminology would be appreciated..!
So,.. When I require a file that is located in the same working directory, I am able to do the fallowing:
const { ports, keys } = require('./activeConfig');
console.log(ports, keys, activeConfig);
In this situation ports, keys,
and activeConfig
are all defined and i can use the module as if I had done:
const { ports, keys } = require('./activeConfig');
const activeConfig = require('./activeConfig');
console.log(ports, keys, activeConfig);
However if I try to do the exact same thing from an external directory like so:
const { ports, keys } = require('../../config/activeConfig');
or
const { ports, keys } = require('./config/activeConfig');
activeConfig
is no longer defined and I get an error.
Why is this behavior different depending on the location that I am importing from? Or does this have to do with the way I am exporting the module?
I would like to keep my code nice and tidy, so I would prefer to avoid having to write the second require
. Is there perhaps a different method to do this all in one line?
The module I am trying to require is a Singleton with the fallowing code:
const database = {...}
const keys = {...}
const ports = {...}
const tokens = {...}
module.exports = activeConfig = (() => {
let _database = database;
let _keys = keys;
let _ports = ports;
let _tokens = tokens;
return {
setDatabase: (value) => {
if (value) {...}
return activeConfig;
},
setKeys: (value) => {
if (value) {...}
return activeConfig;
},
setPorts: (value) => {
if (value) {...}
return activeConfig;
},
setTokens: (value) => {
if (value) {...}
return activeConfig;
},
updateConfig: () => {
...
return activeConfig;
},
get database() {
return _database;
},
get keys() {
return _keys;
},
get ports() {
return _ports;
},
get tokens() {
return _tokens;
},
set database(value) {...},
set keys(value) {...},
set ports(value) {...},
set tokens(value) {...}
};
})();