module.exports 는 Node.js에서 모듈을 정의하고 내보내는 데 사용되는 객체이다.
JavaScript에서는 파일 하나가 하나의 모듈로 간주되며, 다른 파일에서 이 모듈을 사용할 수 있도록 데이터를 내보내야 한다.
module.exports
를 사용하면 특정 값
, 함수
, 객체
등을 다른 모듈에서 가져와 사용할 수 있다.
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = {
add,
subtract,
};
// app.js
const math = require('./math');
console.log(math.add(2, 3)); // 5
console.log(math.subtract(5, 2)); // 3
require 는 Node.js에서 모듈을 불러오는 데 사용되는 함수이다.
이를 통해 다른 파일에서 정의된 모듈을 가져와 사용할 수 있다.
// app.js
const math = require('./math');
console.log(math.add(2, 3)); // 5
파일 경로: require는 주어진 경로에서 모듈을 찾아 불러온다. 상대 경로(./)
나 절대 경로(/)
를 사용할 수 있다.
캐싱: Node.js는 모듈을 한 번만 로드하고 이후에는 캐시된 모듈을 반환한다. 이로 인해 성능이 향상된다.
재사용: 같은 모듈을 여러 번 호출하더라도, 한 번 로드된 모듈이 캐시되어 재사용된다.
Directory의 필요성 을 예시를 통해 알아보자
myProject/
├── app.js
└── math/
├── index.js
├── add.js
└── subtract.js
// math/add.js
const add = (a, b) => a + b;
module.exports = add;
// math/subtract.js
const subtract = (a, b) => a - b;
module.exports = subtract;
// math/index.js
const add = require('./add');
const subtract = require('./subtract');
module.exports = {
add,
subtract,
};
// app.js
const math = require('./math');
const a = 5;
const b = 3;
console.log(`Adding ${a} and ${b}: ${math.add(a, b)}`);
console.log(`Subtracting ${b} from ${a}: ${math.subtract(a, b)}`);
Adding 5 and 3: 8
Subtracting 3 from 5: 2
이제 프로젝트의 루트 디렉토리에서 node app.js
명령어를 실행하면 app.js가 실행되고, math/index.js가 진입점
으로 작동하여 각 기능을 사용할 수 있습니다.
index.js 는 Node.js 프로젝트에서 일반적으로 사용되는 파일 이름으로, 특정 디렉토리의 기본 진입점
역할을 한다. 위에 설명했던 예시를 보면 진입점
을 이해할 수 있다.
// 디렉토리 구조
myModule/
├── index.js
├── add.js
└── subtract.js
// 사용 예
const myModule = require('./myModule'); // index.js가 자동으로 로드됨
// index.js
const add = require('./add');
const subtract = require('./subtract');
module.exports = {
add,
subtract,
};
npm 은 Node.js 패키지 매니저로, JavaScript 개발에 필요한 다양한 패키지(모듈)를 관리하고 설치하는 도구이다.
npm은 세계에서 가장 큰 소프트웨어 레지스트리로, 수백만 개의 패키지가 존재한다. 이를 통해 다양한 라이브러리와 프레임워크를 손쉽게 사용할 수 있다.
npm은 Node.js와 함께 기본적으로 설치되며, 다음과 같은 주요 기능을 제공한다:
패키지 설치: npm install <패키지명>
명령어를 사용하여 필요한 패키지를 쉽게 설치할 수 있다.
버전 관리: 특정 버전의 패키지를 설치하거나 업데이트할 수 있으며, 버전 충돌을 방지할 수 있다.
각 프로젝트의 의존성을 package.json
파일에 기록하여, 필요한 패키지를 쉽게 관리할 수 있다. 이 파일에는 프로젝트의 메타데이터, 의존성, 스크립트 등이 포함된다.
패키지를 설치하면 package.json에 자동으로 기입된다.
package.json
은 특정 패키지를 파악할 때 본다면 쉽게 핵심적인 정보를 파악할 수 있는 파일이다.
// package.json 예시
{
"type": "module",
"name": "langguessr",
"version": "2.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"colors": "^1.4.0",
"franc": "^6.1.0",
"franc-all": "^7.2.0",
"langs": "^2.0.0"
}
}
패키지를 전역적으로 설치할 수 있어, CLI(Command Line Interface) 도구나 유틸리티를 시스템 어디서든 사용할 수 있다. 전역 설치는 -g
플래그를 사용하여 수행한다.
npm install -g <패키지명>
package.json의 scripts 섹션에 정의된 명령어를 npm run <스크립트명>으로 쉽게 실행할 수 있다. 예를 들어, 테스트
, 빌드
, 개발 서버 실행
등의 작업을 자동화할 수 있다.
langs, franc, colors 문서
https://www.npmjs.com/package/langs
https://www.npmjs.com/package/franc
https://www.npmjs.com/package/colors
//Shell
~/IvoryExoticTelevisions$ npm i franc langs colors // franc, langs, colors 패키지 설치
up to date, audited 8 packages in 543ms
5 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
//자동으로 package.json에 패키지 정보 기입
{
"type": "module",
"main": "index.js",
"name": "langguessr",
"version": "2.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"colors": "^1.4.0",
"franc": "^6.2.0",
"langs": "^2.0.0"
}
}
//index.js
import { franc, francAll } from "franc";
import langs from "langs";
import colors from "colors";
const input = process.argv[2];
const codeLang = franc(input, {minLength:2});
if (codeLang == "und") {
console.log("Language not found".red);
} else {
const langCountry = langs.where("3", codeLang);
console.log(`${langCountry.name}`.yellow);
}
~/IvoryExoticTelevisions$ node index.js "안녕하세요"
Korean // 결과값