Node Module - Folders as Modules

About

Code is organized in one directories splits between files and a single entry point is provided.

Loading steps

There are three ways in which a folder may be passed to require() as an argument.

First: package.json

  • create a package.json file in the root of the folder, which specifies a main module. An example package.json file might look like this:
{
  "name" : "some-library",
  "main" : "./lib/some-library.js" 
}

If this was in a folder at ./some-library, then require('./some-library') would attempt to load ./some-library/lib/some-library.js

Note: If the file specified by the “main” entry of package.json is missing and can not be resolved, Node.js will report the entire module as missing with the default error:

Error: Cannot find module 'some-library'

Second: index.js or index.node

If there is no package.json file present in the directory, then Node.js will attempt to load an index.js or index.node file out of that directory.

For example, if there was no package.json file in the above example, then require('./some-library') would attempt to load:

./some-library/index.js
./some-library/index.node

Documentation / Reference





Discover More
CommonJs (NodeJs) - Require

The import functionality implementation of commonjs (and then node) is done via the require function require basically: reads a Javascript file (generally a CommonJs module but it may be any javascript...



Share this page:
Follow us:
Task Runner