Menu
CoddyTech

Writing a File

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 14 of 33.

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. In store.js, add is a method of the store object. Inside a method, this is the object itself, so this.notes is the store's array. Passing the array itself throws, because a file holds text.

challenge icon

Challenge

Easy

This step opens the course’s prepared notes command-line tool project, rather than your project files from Reading a File (including store.js). Your earlier work stays in its own lesson. Read the supplied files before editing store.js. This copy contains the file-reading notes tool.

add still forgets the note when the program ends. Make it save every note to notes.json, so list shows it on the next run.

  1. In store.js, after add puts the new note in the array, write the whole array back to notes.json as JSON. Write every note, not only the new one: writing a file replaces everything that was in it. Indent the JSON by two spaces, so it is easy to read in Files.
  2. In notes.js, in the add branch, replace the line that prints Adding: .... It now prints only Saved note , the new note's number, and a full stop. With the two notes notes.json starts with, node notes.js add Buy bread prints:
    Saved note 3.
    and notes.json then holds:
    [
      "Buy milk",
      "Call Ada",
      "Buy bread"
    ]
  3. When there is no notes.json, add creates it. After clear, node notes.js add Call Ada prints Saved note 1., and list then shows 1. Call Ada.

Try it: type add Buy bread in the box after $ node notes.js and press Enter. You see Saved note 3.. Type list: Buy bread is now note 3, even though this is a new run. Open notes.json in Files to see the saved array. Then type clear, which deletes the file, and add Call Ada: you see Saved note 1..

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

Practice on your own: Express playground