이벤트 이미터
Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 20번째.
저장소는 누가 듣고 싶어 하는지 알지 못해도 메모가 추가되었다고 알려야 합니다.
node:events의 EventEmitter는 각 이벤트 이름별로 리스너 목록을 유지합니다. on(name, fn)은 리스너를 추가하고, emit(name, ...args)는 해당 이름의 모든 리스너를 그 인수와 함께 즉시 호출합니다. emit 이후에 추가된 리스너는 아무것도 듣지 못합니다.
import { EventEmitter } from 'node:events';
const door = new EventEmitter();
door.on('open', (who) => console.log(`${who} came in`));
door.on('open', () => console.log('Ding!'));
door.emit('open', 'Ada');
// Ada가 들어왔고, 이어서 Ding!기존 객체를 이미터로 바꾸려면 메서드를 하나에 복사하세요. Object.assign(new EventEmitter(), { ... }).
챌린지
쉬움store가 저장 후 메모의 텍스트와 번호를 담아added를 발생시키는 이미터가 되도록 하세요.notes.js가added를 수신하고 리스너에서Saved note 4.를 출력합니다.
node notes.js add Buy bread를 실행하세요. 그런 다음 clear를 실행하고 메모 두 개를 추가해 번호가 다시 시작되는 것을 확인하세요.
직접 해보기
import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
const file = 'notes.json';
const readJson = async (name, fallback) => {
if (!existsSync(name)) {
return fallback;
}
try {
return JSON.parse(await readFile(name, 'utf8'));
} catch (err) {
console.error(`${name} is damaged: ${err.message}`);
process.exit(1);
}
};
const [notes, settings] = await Promise.all([readJson(file, []), readJson('settings.json', {})]);
const store = {
notes,
settings,
async save() {
await writeFile(file, JSON.stringify(this.notes, null, 2));
},
async add(text) {
this.notes.push(text);
await this.save();
return this.notes.length;
},
async remove(n) {
const [text] = this.notes.splice(n - 1, 1);
await this.save();
return text;
},
};
export default store;
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.