ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2. Node.js 의 모듈
    IT/NodeJs 2020. 10. 14. 20:14

    1. 모듈

      - 모듈 : 특정 기능을 하는 함수나 변수들의 집합.

      - 파일별로 코드를 모듈화 한다.

      - exports, require 사용

      - ES2015 이후 import, from 사용 가능

    <var.js>
    
    const odd = 'odd';
    const even = 'even';
    
    module.exports = { odd, even};
    <func.js>
    
    const {odd, even} = require('./var');
    
    function checkOddOrEven(num){
      if(num%2) {
        return odd;
      }
      return even;
     }
     
     module.exports = checkOddOrEven;
    <index.js>
    
    const { odd, even} = require('./var');
    const checkNumber = require('./func');
    
    function checkStringOddOrEven(str){
       if(str.length % 2){
         return odd;
       }
       return even;
    }
    
    console.log(checkNumber(10));
    console.log(checkStringOddOrEven('hello'));
    <Colsole>
    
    $ node index
    even
    odd

      - ES2015 모듈은 다음과 같이 작성 가능하다

    <func.js>
    
    import { odd, even } from './var';
    
    function checkOddOrEven(num){
      if(num%2) return odd;
      return even;
    }
    
    export default checkOddOrEven;

    'IT > NodeJs' 카테고리의 다른 글

    6. Modules (NestJs)  (0) 2020.10.28
    5. Provider (NestJs)  (0) 2020.10.28
    4. NestJS 설치 및 실행, 기본구조  (0) 2020.10.28
    3. NestJs  (0) 2020.10.28
    1. Node.JS 란?  (0) 2020.10.14
Designed by Tistory.