티스토리 뷰

Node.js

Module in Node.js

seoca 2019. 9. 4. 02:26

 

What is a module

A module is an essential single unit of building a complete program. If your code doesn't have modules, it would be difficult to read and run. 

 

 

How to use module in Node.js?

module.exports is used to return an object from the current module when other modules or programs require it.

To import module, require keyword is used. 

 

 

Example Code

 
//module.exports returns the result of requiring call
module.exports.initialize = () => {
    return new Promise((resolve, reject) => {
        fs.readFile('./data/employees.json', (err, data) => {
            if(err){
                reject("unable to read file");
            }
            else{
                employees = JSON.parse(data);
                fs.readFile('./data/departments.json', (err, data) => {
                    if(err){
                        reject("unable to read file");
                    }
                    else{
                        departments = JSON.parse(data);
                        resolve();
                    }                    
                });
            }
        });        
    });
}
 
 

 

 

 

 

Reference

https://www.sitepoint.com/understanding-module-exports-exports-node-js/

'Node.js' 카테고리의 다른 글

Upgrade node.js version  (0) 2021.01.23
Using bcrypt inside async  (0) 2020.09.25