In Node.js, the common file extension for modules is .js
. This is based on the Javascript programming language, which Node.js relies on. Modules are essentially different Javascript (.js) value components that constitute the whole Node.js application. This file extension is vital, as it informs Node.js that the file should be treated as a module.
Node.js is built on a modular architecture that employs small, reusable functionality in the form of modules. These modules are individual .js
files containing code to perform specific tasks.
For instance, picture a calculator.js
file that includes functions for addition, subtraction, multiplication, and division. This file can be a Node.js module that exports its functionality using module.exports
and can be reused in any other .js
file or module using the require
statement, providing a convenient way to structure a codebase.
Here's a very simple example of what the calculator.js
file might look like:
// calculator.js
module.exports = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
multiply: function(a, b) {
return a * b;
},
divide: function(a, b) {
return a / b;
}
}
We can then include our calculator.js
module in another JavaScript file like so:
// app.js
const calculator = require('./calculator.js');
console.log(`The sum of 2 and 3 is: ${calculator.add(2, 3)}`);
In summary, the use of the .js
extension is entrenched in Node.js development because it denotes a file containing JavaScript code. Also, Node.js modules are saved with the .js
extension because they contain Javascript code that Node.js would interpret.
This is not to dismiss .node
and .npm
, but they serve different purposes in the scope of Node.js development. .node
is often used for C++ add-on binary files, while .npm
is not an extension but a tool, standing for Node Package Manager, which is used for package management in the Node.js environment.