Server/node.js

[node.js] 확장모듈

클리엘 2020. 6. 22. 01:53
728x90

node.js에서 사용가능한 수많은 기능들은 모듈이라는 개념을 통해서 사용됩니다. 모듈은 node.js가 기본적으로 가지고 있는 내장 모듈과 외부에서 따로 설치해서 사용하는 외부 모듈로 나뉩니다.

 

1. 내장모듈

 

사용 가능한 내장 모듈은 아래 주소에서 목록을 확인할 수 있습니다.

 

https://nodejs.org/dist/latest-v12.x/docs/api/

 

Index | Node.js v12.18.1 Documentation

 

nodejs.org

해당 모듈의 기본적인 사용법은 모듈명을 클릭하면 알 수 있습니다. 예를 들어 Console에 대한 사용법은 위 페이지에서 Conole을 클릭하면 아래와 같이 확인하실 수 있습니다.

 

https://nodejs.org/dist/latest-v12.x/docs/api/console.html

 

Console | Node.js v12.18.1 Documentation

Console# The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: A Console class with methods such as console.log(), console.error() an

nodejs.org

위 설명대로라면 const로 변수를 생성한 뒤 log 등의 메서드로 특정 메시지를 표시할 때 변수 내용을 ${변수명} 형식으로 가져올 수 있다고 합니다. 실제로 그런지 확인해 보겠습니다. 아래 내용을 test.js로 저장하고 실행합니다.

const homepage = 'cliel.com';
console.warn(`homepage : ${homepage}! --->`);


2. 외부 모듈

 

외부 모듈에 대해서는 아래 주소에서 확인해 볼 수 있습니다.

 

https://www.npmjs.com/

 

npm | build amazing things

Build amazing things We're npm, Inc., the company behind Node package manager, the npm Registry, and npm CLI. We offer those to the community for free, but our day job is building and selling useful tools for developers like you. Take your JavaScript devel

www.npmjs.com

예를 들어 외부에서 파일을 내려받을 수 있는 모듈로 download라는 것이 있습니다.

 

위 주소에서 download이라고 입력 후 검색하면 관련된 내용을 확인할 수 있습니다. download모듈은 다음과 같이 설치합니다.

npm install download

모듈설치 후 download모듈의 설명을 토대로 작은 이미지 파일을 내려받는 에제를 작성해보면 다음과 비슷하게 구현할 수 있을 것입니다. 아래 내용을 test.js파일로 저장 후 실행시키면 dist라는 폴더 안에 파일이 내려받아지는 걸 확인할 수 있습니다.

const download = require('download');
 
(async () => {
    await download('http://cliel.com/assets/img/item/home.png', 'dist');
})();

참고로 외부 모듈을 삭제하려면 uninstall을, 모듈을 업데이트하려면 update명령을 사용합니다.

 

728x90