Skip to content
Advertisement

Node.js Module.Exports Undefined Empty Object

I have the following files.

index.js

module.exports = {
    "first": require('./1.js'),
    "second": require('./2.js'),
    "third": require('./3.js')
};

1.js

module.exports = "Hello";

2.js

module.exports = "World";

3.js

const utils = require('./');
module.exports = `${utils.first} ${utils.second}`;

run.js

const utils = require('./');
console.log(utils.first);
console.log(utils.second);
console.log(utils.third);

Why is it that when I run node run.js that it prints the following?

Hello
World
undefined undefined

I expect it to print

Hello
World
Hello World

Advertisement

Answer

This is because at the time of running 3.js the index.js file has not been fully defined yet. In order to fix this you have to require the files specifically. For example changing 3.js to the following will work.

const first = require('./1.js');
const second = require('./2.js');
module.exports = `${first} ${second}`;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement