210723 모듈 사용하기

박혜리·2021년 7월 23일
0

nodejs

목록 보기
11/13

모듈의 개념

객체가 너무 많을때, 이것들을 정리정돈할 수 있는 좀 더 큰 도구가 모듈이다.
새로운 파일을 만들어 그 파일 내에서 객체를 관리할 수 있다.

//mpart.js
var M = {
  v:'v',
  f:function(){
    console.log(this.v);
  }
}

//M이 가리키는 객체를 모듈 바깥에서 쓸 수 있도록 export 하겠다! 
module.exports = M;
//mod.js
var part = require('./mpart.js');
part.f();

cmd창에서 node mod.js를 실행해보면
{ v:'v', f: [Fuction: f] }라고 출력되는 것을 볼 수 있음.

모듈의 활용

template 객체를 모듈로 빼서 관리해보자
main.js와 같은 위치에 lib 폴더를 만들고, 그 안에 template.js 파일을 생성
(파일 위치 참고)

template 객체를 통째로 옮겨준다.
마지막에 module.exports = template; 꼭 적어주기

//template.js
var template = {
  html: function (title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
      <title>WEB1 - ${title}</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>
    `;
  },
  list: function (filelist){
    var list = '<ul>';
    var i = 0;
    while(i < filelist.length){
      list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
      i = i + 1;
    }
    list = list+'</ul>';
    return list;
  },
}

module.exports = template;

이제 main.js에서 모듈을 불러오기만 하면 끝!

var template = require('./lib/template.js');
profile
붙잡지 않으면 이 또한 지나가리라

0개의 댓글

관련 채용 정보