fs모듈(FileSystem Module)
2022. 11. 23. 21:31ㆍWEB개발/TIL
반응형
fs모듈(FileSystem Module)
: 파일 처리와 관련된 전반적인 작업을 하는 모듈
1. 파일 읽기: fs.readFile()
1) callback함수 사용하기: fs.readFile('파일경로',콜백함수);
const fs = require("fs");
fs.readFile('./test.txt', function(err,data) {
if (err) throw err;
console.log(data);
})
// 결과: <Buffer ec 95 88 eb 85 95 ed 95 98 ec 84 b8 ec 9a 94 0d 0a eb b0 98 ea b0 91 ec 8a b5 eb 8b 88 eb 8b b9>
- 버퍼 형태로 읽음(컴퓨터가 읽을 수 있는 문자 형태)
fs.readFile('./test.txt','utf8',function(err,data) {
if (err) console.log(err);
console.log(data);
})
//or
fs.readFile('./test.txt', function(err,data) {
if (err) throw err;
console.log(String(data));
})
- utf8옵션을 넣거나 String함수를 사용하여 문자 형태로 출력
2) promise로 읽기: fs.readFile(’파일경로’).then();
const fs = require("fs").promises;
fs.readFile('./test.txt','utf8')
.then(function(data) {
console.log(data);
});
// 결과
안녕하세요
반갑습니당
2. 파일 작성하기: fs.writeFile()
1) callback함수 사용하기: fs.writeFile('파일명', '내용', 콜백함수);
const fs = require("fs");
fs.writeFile('test2.txt','hello',function(err) {
if (err) throw err;
console.log('test2.txt 작성 완료');
fs.readFile('./test2.txt','utf8',function(err, data) {
if (err) throw err;
console.log(data);
});
})//
// 결과
test2.txt 작성 완료
hello
2) promise 사용하기: fs.writeFile(’파일명’,’내용).then()
const fs = require('fs').promises;
fs.writeFile('test3.txt','helllllooo')
.then(function() {
return console.log("test3.txt 작성 완료");
})
.then(function() {
return fs.readFile('test3.txt','utf8');
})
.then(function(data) {
return console.log(data);
});
// 결과
test3.txt 작성 완료
helllllooo
3. 파일 작성하고 복사하고 이름 변경 후 읽어오기
const fs = require('fs').promises;
fs.writeFile('hello.txt','안녕하세용') //hello.txt 파일 작성
.then(function() {
return fs.readFile('./hello.txt','utf8'); //hello.txt 파일 읽기
})
.then(function(data) {
console.log("hello.txt: ",data); //읽어 온 파일 내용 출력
})
.then(function() {
return fs.copyFile('hello.txt', 'hello2.txt'); //hello.txt파일 hello2.txt로 복제
})
.then(function() {
fs.rename('./hello2.txt','./new.txt'); //hello2.txt파일 new.txt로 이름 바꿈
console.log("hello2.txt -> new.txt");
})
.then(function() {
return fs.readFile('./new.txt','utf8'); //new.txt파일 읽기
})
.then(function(data) {
console.log("new.txt: ",data); //읽어 온 파일 내용 출력
})
// 결과
hello.txt: 안녕하세용
hello2.txt -> new.txt
new.txt: 안녕하세용
반응형
'WEB개발 > TIL' 카테고리의 다른 글
Express 모듈 (2) | 2022.11.23 |
---|---|
http모듈 (0) | 2022.11.23 |
Callback과 Promise (0) | 2022.11.23 |
Class, Object, Instance (0) | 2022.11.21 |
구조분해 할당(Destructuring assignment) (0) | 2022.11.21 |