Menu
CoddyTech

파일 쓰기

Coddy Node.js 여정의 Node.js 기초 섹션에 포함된 레슨. 24개 중 11번째.

add는 프로그램이 끝나는 즉시 메모를 잊어버립니다.

writeFileSync(path, text)는 파일에 기록하며, 기존 내용을 모두 대체합니다. JSON.stringify는 배열을 JSON 텍스트로 변환하고, null, 2는 읽기 쉽도록 두 칸 들여씁니다.

import { writeFileSync } from 'node:fs';

const scores = [12, 40];
scores.push(31);
writeFileSync('scores.json', JSON.stringify(scores, null, 2));

파일에는 항상 배열 전체가 저장됩니다. 메모를 불러오고, 하나를 추가한 뒤, 모두 다시 씁니다. 배열 자체를 전달하면 오류가 발생합니다. 파일에는 텍스트가 저장되기 때문입니다.

challenge icon

챌린지

쉬움
  • add는 메모를 추가하고 모든 메모를 notes.json에 저장합니다.
  • 새 메모의 번호와 함께 Saved note 3.를 출력합니다.

node notes.js add Buy bread를 실행한 다음, list를 실행하고 파일 앱에서 notes.json을 여세요. 그런 다음 clear를 실행하고, 저장된 메모가 없는 상태에서 add를 한 번 더 실행하세요.

직접 해보기

import { existsSync, readFileSync } from 'node:fs';

const file = 'notes.json';

const store = {
    notes: existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : [],
    add(text) {
        this.notes.push(text);
        return this.notes.length;
    },
};

export default store;

Node.js 기초의 모든 레슨