Difference between a module and a package in Node.js?
Modules are libraries for Node.js. See the below excerpt from the API:
Node.js has a simple module loading system. In Node.js, files and modules are in one-to-one correspondence.
Examples of modules:
- Circle.js
- Rectangle.js
- Square.js
A package is one or more modules (libraries) grouped (or packaged) together. These are commonly used by other packages or a project of your own. Node.js uses a package manager, where you can find and install thousands of packages.
Example of a package:
Shapes <- Package name
- Circle.js <-
- Rectangle.js <- Modules that belong to the Shapes package
- Square.js <-
Essentially, you could install the package, Shapes
, and have access to the Circle, Rectangle, and Square modules.
A module is a single JavaScript file that has some reasonable functionality.
A package is a directory with one or more modules inside of it and a package.json file which has metadata about the package.
A package can be very simple for example, underscore just has a single JavaScript file (we see two versions of it, regular and minified version and package.json)
open@open-PC MINGW64 ~/Desktop/module-package-demo/node_modules/underscore
$ dir
LICENSE README.md underscore-min.js
package.json underscore.js underscore-min.js.map
Whereas a more complex package like Express has one JavaScript file in the root, but inside its sub-directories has quite a few more JavaScript files and more within sub-directories of that
open@open-PC MINGW64 ~/Desktop/module-package-demo/node_modules/express
$ dir
History.md index.js lib LICENSE package.json Readme.md
Now it's very common for people to refer to a package as a module.
I searched the Node.js documentation and found their def for module:
In the Node.js module system, each file is treated as a separate module.
npm has some official defs here.
A package is a file or directory that is described by a package.json file.
A module is any file or directory in the node_modules directory that can be loaded by the Node.js require() function.
Note: Since modules are not required to have a package.json file, not all modules are packages. Only modules that have a package.json file are also packages.
Everything what you can require()
is a module. In most cases in the CommonJS world, it's one file per module.
A package can contain several modules, but you usually load the entry point (main
), which is specified in the package.json or its index.js if no main
property is provided, for instance: require('express')
.
But you can also require another file (not the main file) if you know the location. For instance, require("express/lib/application")
(in Node.js you can omit the extension: .js).
A package can access modules from other packages if they are listed in the dependencies
property of the package.json.
Actually npm installs all the packages into node_modules which is confusing, because it should be node_packages.
Modules | Node.js Documentation