Menu
CoddyTech

Reading a File

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

Every run starts with the same three notes, because they live only in memory.

readFileSync(path, 'utf8') from node:fs reads a file as a string. A notes file holds JSON, a text format for data written like JavaScript arrays and objects, and JSON.parse turns that text into an array. Reading a file that is not there throws an ENOENT error, so check with existsSync first. The example uses condition ? a : b, which gives a when the condition is true and b when it is false.

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

const scores = existsSync('scores.json')
    ? JSON.parse(readFileSync('scores.json', 'utf8'))
    : [];
console.log(scores.length);

Without 'utf8' you get a Buffer, the file's raw bytes, instead of a string.

challenge icon

Challenge

Easy

This step opens the course’s prepared notes command-line tool project, rather than your project files from CommonJS Modules (including legacy/stats.cjs). Your earlier work stays in its own lesson. Read the supplied files before editing store.js. This copy contains every command so far, plus a new clear command.

Right now every run starts with the same three notes written in store.js. Your notes should come from a file instead: notes.json, which you can open in Files.

  1. In store.js, replace the fixed list of three notes. The store's notes must hold the array saved in notes.json: read the file as text, then turn the JSON text into an array.
  2. If notes.json does not exist, the store starts with an empty array instead of stopping with an error. Check that the file exists before you read it.

notes.json starts with two notes, so node notes.js list prints:

Notes for you
1. Buy milk
2. Call Ada

With no notes.json, it prints:

Notes for you
No notes yet

You only change store.js. notes.js already prints No notes yet when the store is empty.

Try it: type list in the box after $ node notes.js and press Enter. You see the two notes from the file. Then type clear. This command is already in notes.js: it deletes notes.json and prints Deleted notes.json. Type list again: you see No notes yet. Before you press Check, press Reset files to bring notes.json back, because the checks need it.

Try it yourself

// Load the notes from notes.json instead of this list.
const store = {
    notes: ['Buy milk', 'Call Ada', 'Water the plants'],
    add(text) {
        this.notes.push(text);
        return this.notes.length;
    },
};

export default store;
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Node.js Basics

Practice on your own: Express playground