본문 바로가기
코딩 테스트/[Node] Node.js 교과서

[Node] Module | 3.3 모듈로 만들기

by M개발자 2021. 8. 12.
반응형

파일 / 폴더 이름으로 사용할 수 없는 문자

/  |  \  <  >  ,  :  "  ?  * 등 

 

모듈

: 특정한 기능을 하는 함수나 변수들의 집합 

모듈은 자체로도 하나의 프로그램이면서 다른 프로그램의 부품으로도 사용할 수 있다. 

 

module.exports

module.exports에 값을 대입하면 다른 파일에서 사용할 수 있다.

 

require 함수

require 함수 안에 불러올 모듈의 경로를 적어 사용할 수 있다. 

 

var.js

const odd = '홀수입니다.';
const even = '짝수입니다.';

module.exports = {
    odd,
    even,
};

module.exports 안에 odd와 even을 대입하였으므로 다른 파일에서 odd와 even을 사용할 수 있다. 

 

func.js

const { odd, even } = require('./var');

function checkOddOrEven(num) {
    if (num % 2) {
        return odd;
    }
    return even;
}

export default checkOddOrEven;

odd와 even를 사용하기 위해 require 함수안에 경로를 작성하고, 이름(= cosnt {odd, even})을 설정해준다. 

 

index.js

const { odd, even } = require('./var');
const checkNumber = require('./func').default;

function checkStringOddOrEven(str) {
    if (str.length % 2) {
        return odd;
    }
    return even;
}

console.log(checkNumber(10));
console.log(checkStringOddOrEven('hello'));

출처 | Node.js 교과서 개정 2판 3.3 모듈로 만들기

My GitHub

더보기

작년에 아무것도 몰라서 인터넷 찾아서 했던 node가 기억난다++ 

내가 무얼 안다고 지금도 안하는 프로젝트를 고 1때 😢

https://github.com/m04j00/2020_STAC/blob/master/app/index.js

 

 

반응형

댓글