Notice
Recent Posts
Recent Comments
Link
«   2024/03   »
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
Archives
Today
Total
관리 메뉴

공부하자

[Node] File System (readFile, writeFile) 본문

공부/Node.js

[Node] File System (readFile, writeFile)

strongstar 2018. 4. 19. 02:16

- app_file.js


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const fs = require('fs');
 
let file = 'myFile.txt';
 
// r   : 읽기. 파일이 없으면 예외 발생.
// r+  : 읽기/쓰기. 파일이 없으면 예외 발생.
// rs+ : 읽기/쓰기(동기) 동기식 작업이 필요한 경우 openSync() 호출해야함.
// w   : 쓰기. 파일이 없으면 생성, 파일이 있으면 덮어씀.
// wx  : 'w'와 같음. 경로가 존재하면 실패.
// w+  : 읽기/쓰기. 파일이 없으면 생성, 파일이 있으면 덮어씀.
// wx+ : 'w+'와 같음. 경로가 존재하면 실패.
// a   : 추가. 파일이 없으면 생성.
// ax  : 'a'와 같음. 경로가 존재하면 실패.
// a+  : 읽기/추가. 파일이 없으면 생성.
// ax+ : 'a+'와 같음. 경로가 존재하면 실패.
 
fs.open(file, 'w+'function(err, fd){
  if(err)
    console.log(err);
  else {
    console.log("File open.");
 
    fs.writeFile(file, 'Hello'function(err, fd){
      if(err)
        console.log(err);
      else
        console.log("File write.");
    });//writeFile
 
    fs.readFile(file, 'utf8'function(err, data){
      if(err)
        console.log(err);
      else {
        console.log(data);
        fs.close(fd, function(err) {
          if(err)
            console.log(err);
          else
            console.log("File close.");
        });//close
      }//readFile-else
    });//readFile
  }//open-else
});//open
 
cs


- 실행결과




file 폴더내에 myFile.txt 파일이 생성된 것을 확인!




* 참고

node.js v8.x document (링크)


예제 코드 다운받기 (링크)

Comments