본문 바로가기
개발자의삶/node.js

Node.js #6) 파일 시스템.. 동기와 비동기식 입출력의 차이

by 트라네스 2022. 2. 10.
728x90
반응형

안녕하세요.

오늘은 노드의 파일 시스템의 기본인 입출력과 동기(sync)와 비동기(async)에 대해서 알아보려고 합니다.

 

기본 입출력

기본적인 입출력 Read 와 Write 에 대해서 알아보겠습니다.

File System 의 내용은 아래 링크를 참조하시면 자세히 기술되어 있습니다.

 

 

File system | Node.js v17.4.0 Documentation

 

nodejs.org

코드 예제는 동기를 기본적으로 작성하였으며 실제로 사용하실 때 유틸리티성의 함수는 export 를 활용하시는 것을 추천드립니다.

const fs = require('fs');

function get_current_time(){
    let today = new Date();
    return today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
}
function print_current_time(){
    console.log('현재 시간 : ' , get_current_time());
}

console.log('testFile read test start : ' , get_current_time() );
try{
    let origin_read_data = fs.readFileSync('./testFile.txt', "utf8");
    console.log(origin_read_data.toString());
    fs.appendFileSync('./testFile.txt' , '이걸 한번 써볼까요?' , "utf8");
    let after_read_data = fs.readFileSync('./testFile.txt');
    console.log(after_read_data.toString());
    //data 원복
    fs.writeFileSync('./testFile.txt' , origin_read_data , "utf8");
}catch(err){
    console.error(err);
}

console.log('testFile read test end : ' , get_current_time() );

실행결과는 아래와 같습니다.

예제 코드의 실행 결과

위의 코드 예제를 아래 코드인 비동기로  작성하면 어떻게 될까요?

비동기식 파일 입출력

const fs = require('fs');

function get_current_time(){
    let today = new Date();
    return today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
}
function print_current_time(){
    console.log('현재 시간 : ' , get_current_time());
}

console.log('testFile read test start : ' , get_current_time() );
fs.readFile('./testFile.txt' , (err,data) => {
    if(err){
        throw err;
    }
    console.log( 'First call : ', data.toString() );
});
fs.readFile('./testFile.txt' , (err,data) => {
    if(err){
        throw err;
    }
    console.log( 'Second call : ', data.toString() );
});
fs.readFile('./testFile.txt' , (err,data) => {
    if(err){
        throw err;
    }
    console.log( 'Third call : ', data.toString() );
});

console.log('testFile read test end : ' , get_current_time() );

코드의 실험 목적은 First 와 Second 그리고 Third 가 순차적으로 출력이 되는지 아닌지를 보려고 하는 내용입니다.

결과는 실제로 어떨까요?

비동기 파일 읽기 결과

위와 같이 파일 입출력에 비동기로 발생할 경우 순차적일 수도 있고 아닐 수도 있습니다.

실행은 다 되었으나 결과를 실행하는 백그라운드의 환경에 따라서 결과 출력이 실행 순서대로 나타나지 않을 수 있다는 이야기입니다.

 

동기식 파일 입출력

다시 한번 이 내용을 동기 파일 읽기로 바꾸어 보겠습니다.

const fs = require('fs');

function get_current_time(){
    let today = new Date();
    return today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
}
function print_current_time(){
    console.log('현재 시간 : ' , get_current_time());
}

console.log('testFile read test start : ' , get_current_time() );
let data  = fs.readFileSync('./testFile.txt');
console.log( 'First call : ', data.toString() );
data  = fs.readFileSync('./testFile.txt');
console.log( 'Second call : ', data.toString() );
data  = fs.readFileSync('./testFile.txt');
console.log( 'Third call : ', data.toString() );
console.log('testFile read test end : ' , get_current_time() );

실행 결과는 어떻게 될까요?

동기식 파일 읽기 결과

위와 같이  console.log 안에 모두 파일 읽기가 종료된 이후에 test end 로그가 출력됨을 알 수 있습니다.

위에서 실행한 비동기와의 차이점은 비동기에서는 end 의 로그가 결과가 돌아오기 전에 이미 출력 되었다는 사실을 다시 한번 확인해보시길 바랍니다.

 

그럼 오늘의 이야기는 여기에서 마칩니다.

다음에는 버퍼와 스트림에 대해서 알아보도록 하겠습니다.

 

728x90
반응형

댓글


TOP

TEL. 02.1234.5678 / 경기 성남시 분당구 판교역로