728x90
1. Node.js module system
Module System
모듈화 조건
- 자신만의 독립적인 실행영역
- 전역변수(Global variable)와 지역변수(Local variable)를 분리하는 것
- JS는 파일마다 독립적인 파일 스코프가 있기 때문에
파일 하나에 모듈 하나
를 작성하는 방법으로 독립적인 실행 영역 확보
- 모듈을 외부에서 사용할 수 있도록 공개
- Node.js (CommonJS의 모듈 명세를 따르는)는
exports
라는 전역 객체를 이용해서 정의합니다.
- Node.js (CommonJS의 모듈 명세를 따르는)는
- 모듈 불러오기
- 모듈을 사용하는 영역에서는
require() 함수
를 이용해서 모듈을 불러옵니다.
- 모듈을 사용하는 영역에서는
module.exports를 사용하여 module 만들기
- module.exports : 파일 내 정의된 함수 외부 공개
- require : 공개한 모듈 가져오기
// calculator.js
const initialNumber = 10
function addTen(a, b) {
return a + b - initialNumber;
}
function substractTen(a, b) {
return a + b - initialNumber;
}
module.exports = {
addTen,
substractTen
}
1. 전체 import
// main.js
const calculator = require("./calculator.js");
console.log(`4 + 8 + 10 = ${calculator.addTen(4, 8)}`); // 16
console.log(`4 + 8 - 10= ${calculator.substractTen(4, 8)}`); // 2
2. 구조분해 할당을 통한 import
// main.js
const {addTen, substractTen} = require("./calculator.js");
console.log(`4 + 8 + 10 = ${addTen(4, 8)}`); // 16
console.log(`4 + 8 - 10= ${substractTen(4, 8)}`); // 2
2. Built-in modules - File system module
Node.js는 내장된 모듈(Built-in modules)이 있다. 그 중에서 파일을 읽고 쓸 수 있는 메서드를 비롯한 다양한 기능을 제공하는 FileSystem(fs) 모듈을 호출하여 동기적 처리와 비동기적 처리를 이해해보자.
1) Reading and Writing Files - Synchronously
이름과 나이 두 가지 정보가 저장된 privateInfomation.txt
파일을 fileSystem 객체
의 메소드를 활용해서 읽고, 번호와 수정 날짜를 추가하는 과정을 진행해보자.
1-1) 파일별 코드
//privateInfomation.txt
Name : Harry Potter
Age : 22
// syncFileSystem.js
const fileSystem = require("fs");
//Read File (Before)
const privateInformation = fileSystem.readFileSync("./privateInformation.txt", "utf-8");
console.log(`===== Before written ===== \n${privateInformation}`);
//Write File
const additionalInfo = `${privateInformation}PhoneNumber : 010-7777-0000\nModified at : ${Date.now()}`;
fileSystem.writeFileSync("./privateInformation.txt", additionalInfo);
console.log("===== Successfully File written! ===== \n");
//Read File (After)
const updatedPrivateInformation = fileSystem.readFileSync("./privateInformation.txt", "utf-8");
console.log(`===== After written ===== \n${updatedPrivateInformation}`);
//동기, 비동기 파악 코드
console.log("\n===== 추가적으로 실행되어야 하는 코드 =====");
console.log("추가 실행 코드 1");
console.log("추가 실행 코드 2");
console.log("추가 실행 코드 3");
console.log("추가 실행 코드 4");
1-2) 결과(동기적 진행)
$ node syncFileSystem.js
===== Before written =====
Name : Harry Potter
Age : 22
===== Successfully File written! =====
===== After written =====
Name : Harry Potter
Age : 22
PhoneNumber : 010-7777-0000
Modified at : 1653178357269
===== 추가적으로 실행되어야 하는 코드 =====
추가 실행 코드 1
추가 실행 코드 2
추가 실행 코드 3
추가 실행 코드 4
// privateInfomation.txt (수정됨)
Name : Harry Potter
Age : 22
PhoneNumber : 010-7777-0000
Modified at : 1653178357269
2) Reading and Writing Files - Asynchronously
비동기적 실행을 위해 콜백함수
를 넣고, 동일한 과정을 거쳤을 때 어떻게 출력이 되는지 살펴보자.
- 콜백함수 - 비동기 실행이 완료되고 호출되는 함수.
- 비동기 함수가 실행되면 작업이 끝날때까지 기다리는 것이 아니라 백그라운드에 비동기 작업을 위임해주기 때문에 File I/O 작업이 오래 걸리더라도 추가적으로 실행되어야 하는 코드들에 영향을 주지 않는다.
⇒ File I/O 작업을 제외한 코드가 먼저 실행되고 읽고 쓰는 코드는 이후에 실행
2-1) 파일별 코드
//privateInfomation.txt
Name : Harry Potter
Age : 22
// asyncFileSystem.js
const fileSystem = require("fs");
// Read File (Before)
fileSystem.readFile("./privateInformation.txt", "utf-8", (err, data1) => {
console.log(`===== Before written ===== \n${data1}`);
const additionalInfo = `${data1}PhoneNumber : 010-7777-0000\nModified at : ${Date.now()}`;
// Write File
fileSystem.writeFile("./privateInformation.txt", additionalInfo, "utf-8", (err, data2) => {
console.log("===== Your file has been written =====");
// Read File (After)
fileSystem.readFile("./privateInformation.txt", "utf-8", (err, data3) => {
console.log(`===== After written ===== \n${data3}`);
});
}
);
});
//동기, 비동기 파악 코드
console.log("\n===== 추가적으로 실행되어야 하는 코드 =====");
console.log("추가 실행 코드 1");
console.log("추가 실행 코드 2");
console.log("추가 실행 코드 3");
console.log("추가 실행 코드 4");
2-2) 결과(비동기적 진행)
//zsh
$ node asyncFileSystem.js
===== 추가적으로 실행되어야 하는 코드 =====
추가 실행 코드 1
추가 실행 코드 2
추가 실행 코드 3
추가 실행 코드 4
===== Before written =====
Name : Harry Potter
Age : 22
===== Your file has been written =====
===== After written =====
Name : Harry Potter
Age : 22
PhoneNumber : 010-7777-0000
Modified at : 1653192110477
'Dev > Nodejs' 카테고리의 다른 글
Node.js 와 이벤트 루프 (0) | 2024.04.03 |
---|---|
NPM (Node Package Manager)의 이해 (0) | 2022.08.07 |
Node.js의 이해 (0) | 2022.08.07 |