Welcome to this tutorial on working with Node.js modules. Our goal is to help you understand how to import and use both built-in and custom Node.js modules in your applications.
You will learn how to:
- Import built-in Node.js modules
- Create and use custom Node.js modules
- Understand module scope and encapsulation
Prerequisites: Basic understanding of JavaScript and Node.js.
Node.js has a simple module loading system where files and modules are in one-to-one correspondence. This means each file is treated as a separate module.
A module encapsulates related code into a single unit of code. This can be interpreted as moving all related functions into a file.
Node.js comes with many built-in modules that you can use without any further installation. Here's how you can import a built-in module:
const fs = require('fs');
In the above line, fs
is a built-in module that provides filesystem related functionalities.
To create a custom Node.js module, you create a new file and use module.exports
or exports
to expose things you want to make public:
// myModule.js
module.exports = 'Hello world';
You can then use this module in another file:
// app.js
const myModule = require('./myModule');
console.log(myModule); // Outputs: Hello world
// Importing the Path module
const path = require('path');
// Using the join method to concatenate paths
let completePath = path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
console.log(completePath);
// Expected Output: '/foo/bar/baz/asdf'
// This example shows how to use the built-in Path module to handle file paths.
// myModule.js
module.exports = function (num1, num2) {
return num1 + num2;
}
// app.js
const addNum = require('./myModule');
console.log(addNum(5, 3)); // Outputs: 8
// This example shows how to create a custom module that exports a function, and then use it in another file.
In this tutorial, we've learned how to import and use built-in Node.js modules, create and use custom Node.js modules, and understand module scope and encapsulation.
Next, you can explore more about Node.js Event-Driven Architecture or learn about different Node.js frameworks like Express.js.
http
module to create a simple server that responds with a "Hello World" for every request.Exercise 3: Create a custom module that exports a function to write a JSON object to a file using the fs
module.
Hint: You can use the fs.writeFile
method. Don't forget to stringify your JSON object before writing it to the file.
Happy coding!