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$ dirLICENSE README.md underscore-min.jspackage.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$ dirHistory.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.