0

I am having trouble requiring from parent directories within NodeJS. I have read this post, but still couldn't figure it out.

node.js require from parent folder

This is my file structure:

-- components/
    -- windows/
        -- index.js
    -- index.js
-- main.js

This is the code:

// /main.js
var components = require("./components")
components.windows.inner()

// /components/index.js
module.exports = {
    windows: require("./windows"),
    foo: "foo",
}

// /components/windows/index.js
var components = require("./..")
module.exports.inner = function() {
    console.log(components.foo)
}

When I run main.js, the inner() function prints undefined.

Why is it printing undefined? Shouldn't it print foo? Am I missing something about how Node works?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Matt X
  • 224
  • 1
  • 6
  • 17
  • 1
    You have a circular dependency, that's what doesn't work. `require("./..")` returns an empty object, the export that gets later overwritten by the `module.exports =` assignment in `components/index.js`. Use dependency injection instead. – Bergi Nov 11 '18 at 17:38
  • What is dependency injection? @Bergi – Matt X Nov 11 '18 at 17:41

1 Answers1

2

You just built up a "circular dependency". /components/windows/ requires /components/, which requires /components/windows/, which requires ...

To resolve those nevertheless, NodeJS initializes the exports to an empty object and rewrites them to the exports object after the module initialized. Therefore you can access /components/windows from inside /components/ but not the other way round.

To remove the circular dependency, move foo to another file that you require in both modules.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151