Welcome to the Node.js tutorial on creating custom modules! In this lesson, we'll learn how to organize our code into reusable components, making it easier to manage and share our code with others.
As our codebase grows, it becomes essential to structure it in a way that promotes reusability, maintainability, and easy collaboration. Custom modules allow us to do just that!
In Node.js, custom modules are simply JavaScript files that we can require and use within our projects. Here's a step-by-step guide on creating a custom module:
math.js.// math.js
function add(a, b) {
return a + b;
}
module.exports = {
add
}app.js, we can require our custom module and use it.// app.js
const math = require('./math');
console.log(math.add(5, 3)); // Output: 8š” Pro Tip: Always use a descriptive name for your module file, and make sure to export the functions or objects that you want to use in other files.
As your project grows, you may want to organize your modules into directories. To do this, create a new folder for your modules, say utils, and place the math.js file inside it.
- utils/
- math.js
Then, in your app.js, update the require statement to reflect the new location of your module.
// app.js
const math = require('./utils/math');
console.log(math.add(5, 3)); // Output: 8If you want to use third-party modules, you can install them using npm (Node Package Manager). Once installed, you can import them into your project using the require statement.
For example, let's install a popular library called lodash.
npm install lodashThen, in your app.js, you can import and use it.
// app.js
const _ = require('lodash');
console.log(_.add(5, 3)); // Output: 8Node.js supports ES6 modules as of version 14. If you're using a newer version, you can use ES6 modules for a cleaner import syntax.
In your math.js, export your function using default export.
// math.js (ES6 version)
export default function add(a, b) {
return a + b;
}In your app.js, import the default export using the import statement.
// app.js (ES6 version)
import add from './math.js';
console.log(add(5, 3)); // Output: 8What is the purpose of creating custom modules in Node.js?
That's it for our introduction to creating custom modules in Node.js! In the following lessons, we'll dive deeper into using modules, best practices, and tips for maintaining a well-structured codebase. Happy coding! š»š