Node.js Tutorial – 4 [Sync, ASync]

Sync Async

Sync : 동기
Async : 비동기

File을 이용한 예제

https://nodejs.org/api/fs.html

TXT 파일을 하나 생성한다.

Sync

fs, FileSystem을 import하고 사전에 생성한 sync_hello.txt 파일을 readFileSync 함수를 이용해 encoding utf8 형식으로 불러온 후 Log를 통해 출력해본다.

var fs = require("fs");
var data = fs.readFileSync("sync_hello.txt",{encoding:"utf8"});
console.log(data);

async

var fs = require("fs");
console.log(1);
 fs.readFile("sync_hello.txt",{encoding:"utf8"},function(err,data){
    console.log(2);
    console.log(data);
});
console.log(3);

순서를 자세히 보자

코드상 순서는 1,2, Hello!, 3이지만 Async로 인해 1,3,2 Hello! 순이 되었다.

Leave a Comment