Node.js에서 동기(Synchronous)와 비동기(Asynchronous)


Node.js의 홈페이지의 첫 화면을 보게되면 아래와 같이 쓰여있는 것을 확인 할 수 있다. 




이중에 non-blocking(논 블로킹) I/o 모델을 사용해 가볍고 효율적이라고 하였는데

non-blocking이라는 것이 비동기화 방식을 말하는 말이다.


동기(synchronous)와 비동기(asynchronous)를 blocking과 non-blocking 이라고 말할 수 있다.

그중 blocking은 우리가 많이 경험해 본 것인데 

함수호출 순서에서 함수의 콜백이 이루어졌을때 콜백의 결과를 기다렸다가 다음줄을 실행하는 경우를 뜻하고

그와 반대로 non-blocking 은 

함수호출 순서에서 함수의 콜백이 이루어졌을때 콜백의 결과를 기다리는 것이 아닌 콜백함수를 호출하면서 다음줄을 실행하는 경우를 뜻 한다. 


아래 예제 소스 파일을 보면 이해가 더 쉬울 것이다.


ex) node.js의 fs.writefileSync와 fs.writefile 사용

//동기 방식(blocking) fs.writeFileSync (Sync)가 붙은걸 확인


const fs = require('fs'); console.log('A point'); fs.writeFileSync('message.txt','Hello Node.js');

console.log('B point');


-----------------------------------------------------------------


//비동기 방식(non-blocking) fs.writFile (Sync)가 안붙은걸 확인


const fs = require('fs'); console.log('A point'); fs.writeFile('message2.txt','Hello Node.js',function() { console.log('file wrote'); }); console.log("B point");


동기 방식과 비동기 방식을 구현했다. 

결과는 어떻게 나올까?


//동기 방식(blocking)

A point

B point


// 비동기 방식 (non-blocking)

A point

B point

file wrote

라고 출력된것을 확인 할 수 있고, 

비동시 방식에서 보면 file wrote가 코드순서와는 다르게 맨 마지막에 cosole.log가 찍힌것을 볼 수 있다.


+ Recent posts