Menu
CoddyTech

Writing a File

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 11 of 24.

add forgets the note as soon as the program ends.

writeFileSync(path, text) writes a file, replacing everything it held. JSON.stringify turns an array into JSON text, and null, 2 indents it by two spaces so it reads well in Files.

import { writeFileSync } from 'node:fs';

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

The file always gets the whole array: load the notes, add one, write them all back. Passing the array itself throws, because a file holds text.

challenge icon

Challenge

Easy
  • add appends the note and saves every note to notes.json.
  • It prints Saved note 3. with the new note's number.

Run node notes.js add Buy bread, then list, and open notes.json in Files. Then clear and add once more on the empty disk.

Try it yourself

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;

All lessons in Node.js Basics