Understanding Packages and Modules
Node.js and npm have very specific definitions of packages and modules, which are easy to mix up. We'll discuss those definitions here, make them distinct, and explain why certain default files are named the way they are.
A package is a file or directory that is described by a package.json.
This can happen in a bunch of different ways! For more info, see
"What is a package?, below.
A module is any file or directory that can be loaded by Node.js'
require(). Again, there are several configurations that allow this to
happen. For more info, see "What is a module?", below.
What is a package?
A package is any of the following:
a) A folder containing a program described by a package.json file.
b) A gzipped tarball containing (a).
c) A url that resolves to (b).
d) A <name>@<version> that is published on the registry with (c).
e) A <name>@<tag> that points to (d).
f) A <name> that has a latest tag satisfying (e).
g) A git url that, when cloned, results in (a).
Noting all these package possibilities, it follows that even if you never
publish your package to the public registry, you can still get a lot of
benefits of using npm:
If you just want to write a node program, and/or,
If you also want to be able to easily install it elsewhere after packing
it up into a tarball.
The node_modules folder is the place Node.js looks for modules.
(See "What is a module?", above.)
For example, if you create a file at node_modules/foo.js and then
had a program that did var f = require('foo.js'), it would load
the module. However, foo.js is not a "package" in this case
because it does not have a package.json.
Alternatively, if you create a package which does not have an
index.js or a "main" field in the package.json file, then it is
not a module. Even if it's installed in node_modules, it can't be
an argument to require().
Last modified February 24, 2020
Found a typo? Send a