IdoCleanCode
article thumbnail
Published 2024. 10. 6. 15:57
[Node.js] CommonJS Tutorials/Node
반응형

CommonJS는 자바스크립트의 모듈 시스템 중 하나로 주로 Node.js 환경에서 사용됩니다.

 

1. 정의

CommonJS는 각파일을 독립적인 모듈로 간주하며, module.exports로 내보내고 require()로 가져와 다른 모듈과의 의존성을 명확히 정의할수 있는 시스템입니다.

 

2. 모듈 내보내기

모듈에서 내보내고 싶은 변수, 함수, 객체 등을 module.exports에 할당합니다.

 

단일 내보내기

// greet.js
const greet = (name) => `안녕하세요, ${name}!`;
module.exports = greet;

 

다중 내보내기

// mathUtils.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;

module.exports = {
    add,
    subtract,
};

 

3. 모듈 가져오기

다른 모듈에서 내보낸 요소를 require() 함수를 사용하여 가져옵니다.

// index.js
const greet = require('./greet');
console.log(greet('이승헌')); // "안녕하세요, 이승헌!"

const mathUtils = require('./mathUtils');
console.log(mathUtils.add(5, 3)); // 8
console.log(mathUtils.subtract(5, 3)); // 2

 

4. 비동기 I/O 지원

// fsModule.js
const fs = require('fs');

const readFile = (filePath) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) {
            console.error("파일 읽기 오류:", err);
            return;
        }
        console.log(data);
    });
};

module.exports = readFile;

 

// index.js
const readFile = require('./fsModule');

readFile('./example.txt'); // example.txt의 내용을 비동기적으로 읽어 출력

 

관련자료

 

 

https://idocleancode.tistory.com/436

 

[Node.js] 학습 로드맵

Node.js 소개Node.js 이란?    참고자료https://roadmap.sh/nodejs Node.js Developer Roadmap: Learn to become a modern node.js developerLearn to become a modern node.js developer using this roadmap. Community driven, articles, resources, guides, i

idocleancode.tistory.com

 

 

반응형

'Tutorials > Node' 카테고리의 다른 글

[Express.js] Project Setting  (1) 2024.10.13
[Node.js] 간단한 입출력 콘솔 프로그램  (0) 2024.10.12
[Node.js] ESM  (1) 2024.10.06
[Node.js] Node.js 실행  (0) 2024.10.06
[Node.js] Node.js vs Browser  (0) 2024.10.06
profile

IdoCleanCode

@IdoCleanCode

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!