Node.js 학습_스레드풀과 커스텀 이벤트 / 에러 처리

Node.js 학습_스레드풀과 커스텀 이벤트 / 에러 처리

728x90

반응형

# 스레드풀

fs, crypto, zlib 모듈의 메서드를 실행할 때는 백그라운드에서 동시에 실행됨. (스레드 풀이 동시에 처리해줌)

노드는 기본적으로 백그라운드에서 4개씩 동시에 돌림.

SET UV_THREADPOOL_SIZE=8 명령어를 이용하여 컴퓨터 사양에 맞게 변경 가능. (맥/리눅스의 경우 UV_THREADPOOL_SIZE=8 로 변경 가능)

const crypto = require('crypto'); const pass = 'pass'; const salt = 'salt'; const start = Date.now(); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('1 ', Date.now() - start); }); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('2 ', Date.now() - start); }); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('3 ', Date.now() - start); }); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('4 ', Date.now() - start); }); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('5 ', Date.now() - start); }); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('6 ', Date.now() - start); }); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('7 ', Date.now() - start); }); crypto.pbkdf2(pass, salt, 1_000_000, 128, 'sha512', () => { console.log('8 ', Date.now() - start); });

# 커스텀 이벤트

const EventEmitter = require('events'); const myEvent = new EventEmitter(); // 커스텀 이벤트 myEvent.addListener('event1', () => { console.log('이벤트 1'); }); myEvent.on('event2', () => { console.log('이벤트 2'); }); myEvent.on('event2', () => { console.log('이벤트 2 추가'); }); myEvent.once('event3', () => { console.log('이벤트 3'); }); // once : 한 번만 실행됨. myEvent.emit('event2', () => { console.log('이벤트 2'); }); myEvent.emit('event1'); // 이벤트 호출 myEvent.emit('event2'); // 이벤트 호출 myEvent.emit('event3'); // 이벤트 호출 myEvent.emit('event2'); // 실행 안 됨. myEvent.on('event4', () => { console.log('이벤트 4'); }); myEvent.removeAllListeners('event4'); // 관련된 모든 콜백함수 지움 myEvent.emit('event4'); // 실행 안 됨. const listener = () => { console.log('이벤트 5'); }; myEvent.on('event5', listener); myEvent.removeListener('event5', listener); // myEvent.emit('event5'); // 실행 안 됨. console.log(myEvent.listenerCount('event2')); // 등록된 콜백함수 개수 확인

# 에러 처리(예외 처리)

예외(Exception) : 처리하지 못한 에러

노드 스레드를 멈춤

노드는 기본적으로 싱글 스레드라 스레드가 멈춘다는 것은 프로세스가 멈추는 것.

에러 처리는 필수이다.

기본적으로 try ~ catch문으로 예외를 처리한다. (에러가 발생할 만한 곳을 try ~ catch로 감쌈)

노드가 기본적으로 제공하는 비 동기 함수들의 콜백 에러는 노드 프로세스를 멈추지는 않음.

# error1.js setInterval(() => { console.log('시작'); try { throw new Error('서버를 고장내주마!!!!!'); } catch (err) { console.error(err); } }, 1000); # error2.js const fs = require('fs'); setInterval(() => { fs.unlink('./abcdefg.js', (err) => { if (err) { console.error(err); } }); }, 1000); # error3.js const fs = require('fs').promises; setInterval(() => { fs.unlink('./abcdefg.js') }, 1000); 출력 결과 (프로미스에 catch 붙이지 않은 경우 출력되는 문구.) (node:29168) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, unlink 'C:\work\abcdefg.js' (Use `node --trace-warnings ...` to show where the warning was created) (node:29168) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) # error4.js process.on('uncaughtException', (err) => { console.error('예기치 못한 에러', err); }); setInterval(() => { throw new Error('서버를 고장내주마!!!!'); }, 1000); setTimeout(() => { console.log('실행됩니다.') }, 2000);

최후의 수단으로 사용해야 함. (콜백 함수의 동작이 보장되지 않음, 따라서 복구 작업용으로 쓰는 것은 부적합하다. 에러 내용 기록 용으로만 사용 하는게 좋음)

프로세스 종료 방법은 아래와 같다.

# Windows $ netstat -ano | findstr 포트 // 노드 서버가 몇번 포트를 사용하고 있는지 알아내는 명령어. $ taskkill /pid 프로세스아이디 /f # 맥/리눅스 $ lsof -i tcp:포트 $ kill -9 프로세스아이디

728x90

반응형

from http://dlagusgh1.tistory.com/836 by ccl(A) rewrite - 2021-10-04 11:26:53