본문 바로가기
Node.js

Node.js 핵심 개념 정리

by 오늘만 사는 여자 2021. 9. 10.
728x90
반응형

01. require와 모듈, 모듈의 레졸루션

 

* animals.js

const animals = ['dog', 'cat']

module.exports = animals

 

* main.js

// @ts-check

// require
// require == module.require 같은 역할
// animals.js 파일을 import하는 역할을 한다
console.log(require('./animals'))

const { path, paths, filename } = module
console.log({
  path,
  paths,
  filename,
})

//CommonJS : require
// ECMAScript : export, import

* ECMAScript 방식

* animals.mjs

const animals = ['dog', 'cat']

export default animals

* main.mjs

import animals from './animals.mjs'
console.log(animals)

확장자를 빼면 에러가 난다. mjs를 붙여줘야함

 

* birds.js

module.exports = ['Sparrow', 'Sea Gull']

* main.mjs

확장자를 꼭 붙여주면 js, mjs 둘 다 받아올 수 있다.

/* eslint-disable  import/extensions */
import animals from './animals.mjs'
import birds from './birds.js'

console.log(animals)
console.log(birds)

 

CommonJS: require

- node standard libarary에 있는 모듈은 절대경로를 지정해 가져온다.

- 이 프로젝트 내의 다른 파일은 상대경로를 지정해 가져온다.

- 절대 경로를 지정하면 module.paths의 경로들을 순서대로 검사하여 해당 모듈이 있으면 가장 첫 번째 것을 가져온다.

// @ts-check
//절대 경로로 가져올 수 있는 것
const http = require('http')
console.log(http)

// node_modules 밑에 폴더에 있으면 절대경로 처럼 바로 가져온다.
// src밑에 node_modules라는 폴더 생성 후 animals.js를 넣어뒀다.
/* eslint-disable */
const animals = require('./animals')
console.log(animals)

const { paths } = module
console.log({ paths })

 

 

728x90
반응형

'Node.js' 카테고리의 다른 글

Node.js 내장 객체  (0) 2021.09.15
npm, yarn 등 패키지 매니저  (0) 2021.09.14
간단한 RESTful API 만들기 3  (0) 2021.09.10
간단한 RESTful API 만들어보기2  (0) 2021.09.10
간단한 Restful API 만들기  (0) 2021.09.08

댓글