I'm a bit confused as to how commonjs is working in the node environment. I'm working with a 3rd party library, and their examples show how to access specific modules like this:
const {module1, module2} = require('somedir/someotherdir')
I understand that it will look for index.js in the directory, but how does it know which modules to load? In the index.js file, I see:
module.exports = {
someError,
someOtherError,
yetAnotherError,
module1,
module2,
module3
}
How does the require code above know to pull module1 and module2, and ignore module3, someError, someOtherError, yetAnotherError
This is an example of a programming technique called destructuring, introduced with ECMAScript 2015, a.k.a. ES6.
It's basically a shortcut that lets you put an object's properties directly into variables.
A verbose way to write the code, without destructuring, would be:
const someobject = require('somedir/someotherdir')
const module1 = someobject.module1
const module2 = someobject.module2
So the require statement just gives you a plain old JavaScript object, which you then get the module1 and module2 properties of.
This syntax is just a short version of doing that:
const {module1, module2} = require('somedir/someotherdir')
You could also write, for example:
const someobject = require('somedir/someotherdir')
const {module1, module2} = someobject
When you write a destructuring statement, you decide which properties of the object to save in local variables by putting the name in the curly braces.
If, for example, you wanted to get someError and someOtherError, you would write it like this:
const {someError, someOtherError} = require('somedir/someotherdir')
…and to get everything:
const {someError, someOtherError, yetAnotherError, module1, module2} = require('somedir/someotherdir')
See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment