본문 바로가기

Back-End/Node.js

Node.js.28.2.Nodejs에서 동기와 비동기 2

반응형

Nodejs 공식 홈페이지에서 fs 모듈에 다음과 같은 함수들이 있다.

하지만 둘러보면 뒤에 Sync가 붙어있는 것과 붙어있지 않은 것이 있다.

readFile과 readFileSync을 보면

readFile은 callback이 있지만, readFileSync은 없다. 이를 통해 동기와 비동기의 차이를 알아보자.

 


readFileSync(동기) - 순차적 실행

  • return값을 준다
//readFile & readFileSync

var fs = require('fs');

//readFileSync - syntax바깥에서 명령을 줄 것이기 때문에 syntax/sample.txt로 작성함
console.log('A');
var result = fs.readFileSync('syntax/sample.txt', 'utf8');
console.log(result);
console.log('C');

 

readFile(비동기) - 

  • return값을 주지 않는다
  • 대신 세 번째 인자에 function 함수를 준다.
console.log('A');
fs.readFile('syntax/sample.txt', 'utf8', function(err, result){
  console.log(result);
});
console.log('C');

fs.readFile을 실행하기 전에 다음 코드가 실행되어 fs.readFile 속 코드가 나중에 실행된다

 

Nodejs의 성능을 잘 활용하기 위해서는 반드시 비동기적인 방식으로 작업을 해야만 한다.

하지만 너무 코드가 복잡하고 성능이 필요하지 않닿면 동기적인 처리를 해도 된다.

반응형