We all know that keeping all the Node.js code in a single file is not good practice, right? We need multiple files to create a large project , so in this chapter, we will explore how we can create those file and import concepts like modules and export requirements. lets start

image.png

These two files, app.js and xyz.js, have different code that is not related to each other, so in NodeJS we call them separate modules.

Q: How do you make two modules work together?

-using a require function

Q: What is the required function?

In Node.js, the require() function is a built-in function that allows you to include or require other modules into your main modules.

Now, let's write our code using the require function.

Task: Our objective is to execute the code written in the xyz.js module by running the app.js module.

image.png

Steps:

  1. Open the app.js module.
  2. First, include the xyz module using the require function.
  3. Then, run the code using Node.js. (As discussed in the last lecture, I hope you have revised it well🙄.)

image.png


Let’s look at one more example.

Disclosure: Before we proceed, I want to highlight that many Node.js developers may not be aware of the next concept I’m about to share, so please pay close attention.