ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Node.js 기본] File System
    Node.js/nodeJS 기본 2022. 12. 11. 23:51
    반응형

    [Node.js 기본] File system

    1. File System

      file system의 핵심 처리 방법은 아래 네가지이다.

     

    • C : create
    • R : read
    • U : update
    • D : delete

     

      node.js에서 C.R.U.D는 fs 모듈을 통해 다루어진다. fs 모듈에는 매우 다양한 메소드가 존재하는데, 이중 주로 사용되는 읽기, 쓰기 함수를 정리하면 아래와 같다.

     

    1-1) Create, Update

    fs.writeFileSync(), fs.writeFile() 이 두 메소드는 기존 파일이 존재할 경우 업데이트 하고, 존재하지 않을 경우 새로운 파일을 생성한다. Sync의 경우 작업이 완료될 때까지 코드 실행을 차단하고 반대의 경우 코드 실행이 차단되지 않고 콜백 함수를 사용해 작업 결과를 처리한다. 각 함수는 아래 코드블럭과 같이 구성되며 writeFile의 콜백함수의 경우 err를 파라미터로 받으며 이를 통해 err 핸들링이 가능하다.

    //fs.writeFileSync(path, data, option[encoding = 'utf8', mode = 0o666, flag = 'w'])
    fs.writeFileSync(__dirname + '/path/folder/file.txt', 'contents of the file','utf8')
    
    //fs.writeFile(path, data, option[encoding = 'utf8', mode = 0o666, flag = 'w'], callback function)
    fs.writeFile(__dirname + '/path/folder/file.txt', 'contents of the file','utf8', err => {})



    예시)

    let http = require('http');
    let fs = require('fs');
    
    let app = http.createServer((req, res) => {
    	fs.writeFile(__dirname+'/data/test.txt', 'function excuted!', 'utf8', err => {
        	if(err) {
            	console.log('error')
             } else { 
                console.log('writeFile excuted!')
                res.writeHead(200)
                res.end('hellow world')
            }
        })
    })
    
    app.listen(800);

    fs.writeFile()실행에 따른 callback 실행 및 file 생성



      추가적으로 기존 파일의 끝 부분에 새로운 컨텐츠를 추가하고 싶다면 fs.appendFile() 혹은 fs.appendFileSync()를 사용하면 된다.

     

    1-2) Read

    fs 모듈에서 파일 읽기는 fs.readFile(), fs.readFileSync() 메소드를 통해 이루어진다. 앞선 경우에서와 같이 동기적 함수는 실행이 완료될 때 까지 코드를 멈추고 결과를 리턴하고 비동기적 함수는 코드 실행을 중지하지 않고 오퍼레이션의 결과를 콜백함수에서 사용한다. 각 함수는 아래 코드블럭과 같이 구성되며, fs.readFile()의 callback은 err와 data을 파라미터로 가지는데 err는 실행중 오류 데이터를 포함하고, data는 파일 콘텐츠의 내용을 포함한다

    //fs.readFileSync(path, option[encoding = 'utf8', flag = 'r'])
    fs.readFileSync(__dirname + '/path/folder/file.txt', 'contents of the file','utf8')
    
    //fs.readFile(path, option[encoding = 'utf8', flag = 'r'], callback function)
    fs.readFile(__dirname + '/path/folder/file.txt', 'contents of the file','utf8', (err, data) => {})



    예시)

    let http = require('http');
    let fs = require('fs');
    
    let app = http.createServer((req, res) => {
    	fs.readFile(__dirname+'/data/test.txt', 'utf8', (err, data) => {
        	if (err) {
            	console.log('error')
            } else {
                res.writeHead(200)
                res.end(data)
            }
        })
    })
    
    app.listen(800);

    fs.readFile() 메소드 및 callback 실행 결과

     

    1-3) Delete

      fs 모듈에서 파일을 삭제하기 위해선 fs.unlink(), fs.unlinkSync() 메소드를 이용한다. 이 메소드는 오직 path만을 인자로 받아 해당 파일이 존재시 삭제한다. 앞서 두 경우와 마찬가지로 동기적, 비동기적 함수로 나뉘며 각 함수는 아래 코드블럭과 같이 구성된다.

    //fs.unlinkSync(path);
    fs.unlinkSync(__dirname + '/data/test.txt');
    //fs.unlink(path, callback);
    fs.unlink(__dirname + '/data/test.txt', err => {});



    예시)

    let http = require('http');
    let fs = require('fs');
    
    let app = http.createServer((req, res) => {
    	fs.unlink(__dirname+'/data/test.txt', (err) => {
            if(err) {
                console.log('error');
            } else {
            	console.log('file deleted!');
            }
        })
    })
    
    app.listen(800);

    fs.unlink() 메소드 실행 결과

     

    2. 메소드 정리

      function parameters feature
    C, U writeFile() path, data, option, callback write file at the specific path
    writeFileSync() path, data, option
    R readFile() path, option, callback read file at the specific path
    readFileSync() path, option
    readdir() path, callback read contents of a directory and return an array of file, directory names
    D unlink() path, callback delete file at the specific path
    unlinkSync() path

     

    반응형

    댓글

Designed by Tistory.