Reading a File
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 10 of 24.
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.
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
Easystore.jsloads its notes fromnotes.jsoninstead of the fixed list.- With no
notes.json, the store starts empty andlistprintsNo notes yet.
Run node notes.js list. Then run node notes.js clear, which deletes the file, and list again. Reset files brings the file back.
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;
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands