Node.js는 기본적으로 Non-Blocking Code 이다. 이는, 코드 한줄의 작업을 실행하면서 I/O 작업이 걸리면 그 동안 바로 다음 작업으로 넘어간다는 뜻이다. 절차지향 프로그래밍에 익숙해진 프로그래머는 단순한 코딩에도 예상치 않은 결과를 얻게 된다. 이러한 Node.js의 특성 때문에, Node.js 는 일반적인 메소드보다 콜백 메소드(Callback Method)를 주로 사용한다.
Blocking Code
아래는, 우리가 일반적으로 생각하는 절차지향이 듬뿍 묻어있는 Blocking-Code 이다.
var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program has ended");
input.txt 에는 다음과 같은 메시지가 들어있다고 가정하자.
Let's understand what is a callback function.
What the HECK is it?
이 프로그램의 결과는 우리가 예상할 수 있는 그 결과와 같다.
$ node main.js
Let's understand what is a callback function.
What the HECK is it?
Program has ended
Blocking Code 에서는 fs.readFileSync() 메소드의 작업 종료시까지 3번줄에서 실행을 대기하고 있기 때문이다. 이는 소스 코드를 짜고, 분석하는데는 좀 더 명료하고 간단해 질 수 있겠지만, 조금 비효율적인 방식이다.
Non-Blocking Code
다음은 콜백 메소드가 사용된 Non-Blocking Code의 예제이다.
var fs = require("fs");
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program has ended");
메소드가 실행될 때, 프로그램이 메소드의 종료를 기다리지 않고, 바로 그 아래에 있는 코드들을 실행하게 된다. 그러다가 fs.readFile()의 실행이 종료되는 이벤트가 생기면 인터럽트가 걸리면서 콜백 메소드가 호출되는 것이다. 그렇기 때문에 Blocking Code와는 달리 아래와 같은 결과를 얻게 된다.
$ node main.js
Program has ended
Let's understand what is a callback function.
What the HECK is it?