FileSystem의 약자로
파일 처리와 관련된 여러가지 기능을 하는 js라이브러리.
import fs from "fs";
// 파일 읽기 - "filename"에 파일 경로를 입력.
fs.readFile("filename", [options], callback);
// "filename" 파일을, [options]을 적용해 읽은후, callback 함수를 실행
fs.readFileSync("finename", [options]);
// "filename"파일을, [options]을 적용해 읽은후, 문자열 반환
// Sync : 동기적 읽기를 뜻함 ( 한 작업을 마치기 전까지, 다른 작업 불가 )
import fs from "fs";
// 파일 쓰기
fs.writeFile("filename", data, [options], callback);
// "filename"파일에, [options]을 적용해 data내용을 작성하고, callback함수 실행
fs.writeFileSync("filename", data, [options]);
// "filename"파일에, [options]을 적용해 data내용을 작성
// 예외처리
/*
파일 입출력은, 다양한 윈인으로 예외가 존재해 에러가 발생할 확률이 높음.
( 권한이 없거나, 파일이 없거나, 디스크 용량이 부족하거나 )
try/catch 문을 활용, 예외 처리를 하거나 (동기식)
콜백함수에 err를 감지해 조건문으로 예외 처리를 해야 함. (비동기적)
*/
// 동기식 예외처리
try {
const file = fs.readFile("filename", [options]);
console.log(file);
} catch (err) {
console.log(err);
}
// 비동기식 예외처리
const file = fs.readFile("filename", [options], function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
// 있으면 true, 없으면 false 반환
fs.existsSync('경로')
fs.mkdirSync('경로/폴더이름')
var file = fs.createReadStream()
메서드 fs.readFile 은 비동기적으로 파일 내용 전체를 읽음.
이 메서드를 실행할 때에는 전달인자 세 개를 받는다.
-Asynchronously reads the entire contents of a file.
path \<string> | \<Buffer> | \<URL> | \<integer>
path에는 파일 이름을 전달인자로 받는다.
네 가지 종류의 타입을 넘길 수 있지만 일반적으로 문자열(string)의 타입을 받음.
-filename or file descriptor
fs.readFile('/etc/passwd', ..., ...)
'etc/passwd' 라는 파일을 불러오는 예제⬆️
options \<Object> | \<string>
대괄호로 감싼 두 번째 전달인자 options는 넣을 수도 있고, 넣지 않을 수도 있다.
대괄호는 선택적 전달인자를 의미.
options는 문자열 또는 객체 형태로 받을 수 있다. 문자열로 전달할 경우 인코딩을 받음. 밑의 예제에서는 'utf8' 을 두 번째 전달인자로 받는 것을 확인할 수 있다. options를 객체 형태로 받는 것은 두 번째 예제를 참고.
-If options is a string, then it specifies the encoding:
// /etc/passwd 파일을 'utf8'을 사용하여 읽습니다.
fs.readFile('/etc/passwd', 'utf8', ...);
[코드] 두 번째 전달인자 options에 문자열을 전달한 경우⬆️
let options = {
encoding: 'utf8', // utf8 인코딩 방식으로 엽니다
flag: 'r' // 읽기 위해 엽니다
}
// /etc/passwd 파일을 options를 사용하여 읽습니다.
fs.readFile('/etc/passwd', options, ...)
[코드] 두 번째 전달인자 options에 객체를 전달한 경우⬆️
callback \<Function>
err \<Error> | \<AggregateError>
data \<string> | \<Buffer>
콜백 함수를 전달,
파일을 읽고 난 후에 비동기적으로 실행되는 함수
콜백 함수에는 두 가지 매개변수가 존재, 에러가 발생하지 않으면 err 는 null 이 되며,
data 에 문자열이나 Buffer 라는 객체가 전달.
data 는 파일의 내용.
-If no encoding is specified, then the raw buffer is returned.
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) {
throw err; // 에러를 던집니다.
}
console.log(data);
});
[코드] 메서드 fs.readFile로 파일의 데이터를 읽을 수 있다.