Node Module - Folders as Modules

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > Node.js > Node - Module (ie NPM Module)

1 - About

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

3 - Loading steps

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

3.1 - 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'

Advertising

3.2 - 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

4 - Documentation / Reference

web/javascript/node/module/folder.txt · Last modified: 2019/02/16 17:40 by gerardnico