Home > database >  requiring a directory rather than a js file
requiring a directory rather than a js file

Time:05-14

I come across a piece code like this in an index.js file:

exports = module.exports = require("./src")

Not sure what the exports = module.exports bit means. And not sure what it means to import an entire directory /src.

CodePudding user response:

TL;DR

These are solutions for your questions, from first to second (in order).

  1. Most likely setting the variable exports to module.exports.
  2. Importing a default file in the folder (e.g. index.js) if specified or not.

1. What does the exports variable define?

From Dave Meehan, a few corrections made:

Comment #1

Your explanation of 1 is incorrect. If they were separate statements as illustrated, exports would equal the previous value of module.exports, and module.exports would equal the return value of require. Chaining them together sets both exports and module.exports to the value returned by require. It's not clear why someone would want to do that, but they did.

Comment #2

We should be very careful in interpreting what the result might be in such a statement as its dependent on whether the variables export and module (with/without property exports) already exists, and whether we are using strict mode. There's a number of other SO posts that expand on "chaining assignment".

Note: I am also mildly confused on this line, so this is my educated guess. Feel free to correct me in the comments, or by editing my post.

Note: This solution is incorrect. Please see Dave Meehan's comments on corrections for this solution.

This line most likely can be also spread into multiple lines, like so.

exports = module.exports;
module.exports = require("./src");

Basically, it is just making a variable called exports, and setting that to module.exports.

This same thing can be done using object destructing too.

const { exports } = module;

This will simply get the exports key from module, and make a new variable called exports.


2. How do you require a folder?

Technically, Node isn't importing an entire folder. Basically, it is checking for a default file in the directory.

There are two cases in how Node.js will check for a file.

  1. If the main property is defined in package.json, it will look for that file in the /src directory.

    {
      "main": "app.js"
    }
    

    If the package.json, was like that, for instance, then it would search for /src/app.js.

  2. If the main property isn't defined in package.json, then it will by default look for a file named index.js. So, it would import /src/index.js.


Summary

In summary, these are the solutions to your questions.

  1. Most likely setting the variable exports to module.exports.
  2. Importing a default file in the folder (e.g. index.js) if specified or not.

This should help clear your confusion.

  • Related