Defining a directory-level module
As mentioned at the beginning of this chapter, modules can also act more like namespaces. We can treat a whole directory as a module, consisting of smaller modules in individual files. The simplest way to do this is to create an index.js
file in the directory.
When calling require('./directoryName')
, Node.js will attempt to load a file named './directoryName/index.js'
(relative to the current script). There is nothing special about index.js
itself. This is just another script file that exposes an entry point to the module. If directoryName
contains a package.json
file, Node.js will load this file first and see if it specifies a main
script, in which case Node.js will load this script instead of looking for index.js
.
To import local modules, we use a file or directory path, that is, something starting with '/'
, '../'
, or './'
as in the preceding example. If we call require
with a plain string, Node.js treats it as relative to the node_modules
folder. The npm...