티스토리 뷰

Node File System Module

  • readFile, readFileSync

    const fs = require('fs'); // file system
    
    fs.readFile('./hello.txt', (err, data) => {
        if(err) {
            console.log('errrrrrorr');
        }
        console.log('1', data.toString('utf8')); // print second
    })   
    
    const file = fs.readFileSync('./hello.txt');
    console.log('2', file.toString()); // print first
    

    readFile이 더 윗줄에 있지만 readFileSync보다 늦게 로그된다. 왜냐하면 readFile은 asyncronous이고 readFileSync는 syncronous하기 때문이다. (상세한 이유에 대해서는 자바스크립트 메뉴의 How JS works? 글참조)

    만약 hello.txt처럼 간단한 것이 아닌 대량의 데이터를 서버로 보내게 된다면, sync를 사용하면 서버가 멈출 수 있다. (작업이 완료될 때까지 계속 기다려야 되기 때문에)

 

  • appendFile, writeFile, unlink

    // APPEND
    fs.appendFile('./hello.txt', ' This is so cool!', err => {
        if(err) {
            console.log(err);
        }
    })
    
    // WRITE
    fs.writeFile('bye.txt', 'Sad to see u go', err => { // bye.txt앞에 경로를 나타내는 ./ 없음
        if(err) {
            console.log(err);
        }
    })
    
    // DELETE
    fs.unlink('./bye.txt', err => {
        if(err) {
            console.log(err);
        }
        console.log('Inception'); 
    })
    

    appendFile을 쓴 뒤 node를 실행시키면 이미 존재하는 hello.txt 파일 내에 'This is so cool!' 이라는 말이 자동으로 적히는 걸 볼 수 있다.

    반면 writeFile을 쓰면 bye.txt가 없었음에도 새로운 파일이 생성되고 'Sad to see u go'가 적혀있게 된다.

    unlink를 사용하면 writeFile로 생성되었던 bye.txt가 사라진다.

 

'공부일지(TIL) > Others' 카테고리의 다른 글

HTML5로 카드 만들기 (with Canvas API)  (0) 2019.06.11
Design Patterns Intro  (0) 2019.05.17
Functional Programming 3  (0) 2019.03.18
Functional Programming 2  (0) 2019.03.13
Functional Programming 1  (0) 2019.03.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함