node.js module

Judo·2020년 12월 21일
0

모듈이란?

  • 기능을 떼서 조립할 수 있는 형태로 만든 부분

node.js에서 모듈 불러오기


  • 브라우저에선 <script> 태그를 이용한다.
  • node.js에선 require를 이용한다.
const fs = require('fs') // 파일 시스템 모듈 불러오기
const dns = require('dns') // DNS 모듈 불러오기 

3rd-party 모듈 사용하기


  • 프로그래밍 분야에서 3rd-party는 공식적으로 제공하는 것이 아닌 다른 모든 "제 3자"의 것을 의미한다. 즉, node.js 문서에 존재하지 않는 것은 3rd-party를 의미한다.
$ npm install underscore
// node_modules에  underscore가 설치된 것.
// 이제 node.js 내장 모듈을 사용하듯 사용할 수 있다.
const _ = require('underscore');

__dirname

  • 현재 실행중인 파일을 포함하는 디렉토리의 절대 경로를 알려주는 변수다.
  • node 폴더안에 1.js 파일 안에서 console.log(__dirname)을 찍어보면
    /Users/hyunsoo/Desktop/note 와 같이 나온다.

디렉토리 작업


File System(fs)와 path 모듈, __dirname을 이용해 디렉토리 작업을 할 수 있다.

새로운 디렉토리 만들기

const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');
fs.mkdirSync(dirPath);
  • 위 코드를 실행하면 현재 경로에 pictures 폴더를 하나 만든다.
profile
즐거운 코딩

0개의 댓글