NodeJS

NodeJS (1) Module

오리888 2023. 4. 9. 03:18

It's always better to keep your codes simple. In order to keep the code clean, it's important to create modules (files)

to separate things in parts. Let's see some examples to see what I mean by keeping code clean

 

Ex.

 

To make this code simpler using modules, we can put them in separate files and call elements that are needed

 

Ex.

 

 

As you can see in the example, I separated my code in three separate files. However, in order to execute the sayHi function in the app.js file, I need to call sayHi function as well as name variables.

This is when module objects come into play.

 

Ex.

 

In order to export elements, simply use module.exports = element or module.exports = element.

In app.js, variable = require(file name) will allow us to get the elements in that specific file.