Search code examples
javascriptnode.jsrequirenode-modules

Why is require() returning `{}` in the interactive shell?


In the terminal, I navigate to a directory containing a file WordManager.js. From there, I type node to get into the interactive shell and type require("./WordManager.js"). The result is {}. The contents of WordManager.js are

class WordManager
{
    // ...
}

I've found conflicting information online about exactly how I should do the export, but I've tried every possible way and nothing works. I've tried exports.WordManager = class WordManager { ... }, I've tried module.exports.WordManager, I've tried export default...

How do I get the behavior I'm looking for - accessing the WordManager class from the interactive shell?


Solution

  • When working with Node you have to declare the exports of a module.

    For example, in your file in order to export WordManager you will want to assign it to module.exports:

    class WordManager {
        // ...
    }
    
    module.exports = WordManager
    

    require() will return the value of module.exports from the required module. Note that if you want to export multiple values you can do so by attaching them as properties to module.exports:

    class WordManager {
        // ...
    }
    
    class SpellChecker {
        // ...
    }
    
    module.exports.WordManager = WordManager
    module.exports.SpellChecker = SpellChecker
    

    This can get a bit wordy when exporting multiple exports, so module.exports is aliased as exports in module scope, so you can do the following instead:

    exports.WordManager = WordManager
    exports.SpellChecker = SpellChecker
    

    A word of warning, exports can be overwritten but will not update the value or module.exports so the following will not work:

    // Does not work
    exports = WordManager
    

    Hope that helps.