Suzie's Blog

[NodeJS] Node Documentation | File system | writeFile | readFile 본문

개발

[NodeJS] Node Documentation | File system | writeFile | readFile

Iuna 2023. 8. 30. 17:21
반응형
SMALL
node .\index.js\

NodeJS Docs 웹사이트에 접속하면 각 버전별로 API를 사전처럼 찾아 볼 수 있다.

https://nodejs.org/en/docs

 

Documentation | Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

오늘은 간단하게 위의 documentation을 참고해서 File system API를 활용하여 node를 동작시켜보려고 한다.

 

오늘의 목표는 txt파일을 만들고 그 파일을 읽는 로직을 실행시키는 것이다.

 

일단 아래와 같이 코드를 입력해서 File System API를 불러온다.

const fs = require("fs");

1. txt파일 생성하기

위에 선언해 준 fs에서 writeFile을 불러와 주고 documentation에 나온 부분을 참고해서 아래와 같이 입력해준다

fs.writeFile("message.txt", "Hello from Iuna!", (err) => {
  if (err) throw err;
  console.log("The file has been saved!");
});

터미널에 아래와같이 node를 실행시켜준다.

node .\index.js\

node가 실행되며 터미널에 'The file has been saved!'라는 문구가 뜨며 message.txt 파일이 생성된 것을 볼 수 있다.

 

2. txt파일 읽기

1번과 똑같이 fs에서 이번엔 readFile을 불러와준다.

utf8을 명시해 줘야 encoding 되어 글자를 읽을 수 있다.

utf8를 명시해 주지 않으면 raw buffer로 출력된다

예시 : <Buffer 48 65 6c 6c 6f 20 66 72 6f 6d 20 53 75 7a 69 65 21 21>

fs.readFile("message.txt", "utf8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

다시 터미널에 아래와 같이 node를 실행시켜주면

node \.index.js\

The file has been saved!
Hello from Iuna!

 

가 터미널에 나타난 것을 확인 할 수 있다

 

반응형
LIST