fs
- 파일시스템과 상호작용 하는 모듈
- 비동기 방식을 기본으로 동작, 동기 메서드도 제공
file
open
fs.open(path,flags,mode,callback) => void
callback : (err:NodeJS.ErrnoException, fd:number) => void
mode : string
- w(쓰기), r(읽기), a(추가하기)
fs.openSync(path,flags,mode) => fd:number
path
: 개방할 파일 경로
flags
r(reading), w(writing), a(appending), ...
close
fs.close(fd, callback) => void
fs.closeSync(fd) => void
read
fs.readSync(fd:number, buffer, offset, length, position) => number
fs.read(fd, buffer, offset, length, position, callback) => void
write
fs.writeSync(fd, buffer, offset, position)
e.g. readFileSync, writeFileSync
import fs from "fs";
import { Buffer } from "buffer";
function readFileSync(path: string, bufferSize?: number) {
const chunks: Buffer[] = [];
const buffer = Buffer.alloc(bufferSize || 10);
let position = 0;
try {
const fd = fs.openSync(path, "r");
while (true) {
const size = fs.readSync(fd, buffer, 0, buffer.length, position);
if (size > 0) {
const chunk = Buffer.alloc(size);
buffer.copy(chunk, 0, 0, size);
chunks.push(chunk);
position += size;
} else {
break;
}
}
fs.closeSync(fd);
fs.close();
} catch (err) {
console.error(err);
}
return Buffer.concat(chunks);
}
function writeFileSync(path: string, data: string, bufferSize?: number) {
const buffer = Buffer.alloc(bufferSize || 10);
let start = 0;
try {
const fd = fs.openSync(path, "w");
const content = Buffer.from(data);
while (start < content.length) {
let end = start + buffer.length;
end = end < content.length ? end : content.length;
content.copy(buffer, 0, start, end);
fs.writeSync(fd, buffer, 0, end - start);
start = end;
}
fs.closeSync(fd);
console.log("Completed");
} catch (err) {
console.error(err);
}
}
const buf = readFileSync("files/text.txt");
writeFileSync(
"files/customWriteFileSync",
"Hello World\nNice to meet you\nSee you next time."
);