Node.js 모듈 사용법

Jelkov Ahn·2021년 10월 14일
0

JS/NODE 비동기

목록 보기
4/6
post-thumbnail

Node.js 내장 모듈을 사용하는 방법

내장 모듈 목록 (https://nodejs.org/dist/latest-v14.x/docs/api/)
DNS 모듈 사용법(https://nodejs.org/dist/latest-v12.x/docs/api/dns.html)

Node.js 메서드

readFile : 파일을 읽을 때

writeFile : 파일을 저장할 때

브라우저에서 파일을 불러올 때

브라우저에서 다른 파일을 불러올 때에는 다음과 같이 <script> 태그를

<script src="불러오고싶은_스크립트.js"></script>

[코드] HTML에서 JavaScript 파일을 불러오는 script 태그

Node.js 에서 파일을 불러올 때

Node.js 에서는 자바스크립트 코드 가장 상단에 require 구문을 이용하여 다른 파일을 불러옵니다.

const fs = require('fs'); // 파일 시스템 모듈을 불러옵니다
const dns = require('dns'); // DNS 모듈을 불러옵니다
// 이제 fs.readFile 메소드 등을 사용할 수 있습니다!

[코드] Node.js에서 다른 파일을 불러오는 require 구문(CommonJS)

3rd-party 모듈을 사용하는 방법

써드 파티 모듈(3rd-party module)은 해당 프로그래밍 언어에서 공식적으로 제공하는 빌트인 모듈(built-in module)이 아닌 모든 외부 모듈을 일컫습니다.
예를 들어, Node.js에서 underscore는 Node.js 공식문서에 없는 모듈이기 때문에 써드 파티 모듈입니다. underscore 와 같은 써드 파티 모듈을 다운로드받기 위해서는 npm을 사용해야 합니다.

터미널에서 다음과 같이 입력해 underscore 를 설치할 수 있습니다.

npm install underscore

[커맨드] underscore 모듈을 설치합니다.

이제 node_modules에 underscore가 설치되었습니다. 이제 Node.js 내장 모듈을 사용하듯 require구문을 통해 underscore 를 사용할 수 있습니다.

const _ = require('underscore');

[코드] Node.js의 3rd-party 'underscore'를 사용할 수 있습니다.

fs.readFile을 통해 알아보는 Node.js 공식문서 가이드

관련 사이트 : fs.readFile의 공식 API 문서

NodeJS Path 설명 : https://m.blog.naver.com/bi9choi/221952274412

profile
끝까지 ... 가면 된다.

0개의 댓글