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

Get Learning Node.js for .NET Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.