
681
16.7 파일 작업
사용할 수 있다면 파일에서 덩어리 여러 개를 읽기가 쉬워집니다.
const fs
=
require("fs");
function readData(filename) {
let fd
=
fs.openSync(filename);
try {
//
파일
헤더를
읽습니다
.
let header
=
Buffer.alloc(12); // 12
바이트
버퍼
fs.readSync(fd, header, 0, 12, 0);
//
파일의
매직
넘버를
확인합니다
.
let magic
=
header.readInt32LE(0);
if (magic !
==
0xDADAFEED) {
throw new Error("File is of wrong type");
}
//
헤더에서
데이터
길이와
오프셋을
얻습니다
.
let offset
=
header.readInt32LE(4);
let length
=
header.readInt32LE(8);
//
파일에서
해당
바이트를
읽습니다
.
let data
=
Buffer.alloc(length);
fs.readSync(fd, data, 0, length, offset);
return data;
} finally {
//
설령
위에서
예외가
일어나더라도
파일은
항상
닫힙니다
.
fs.closeSync(fd); ...