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
EasyThis 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.
- In
store.js, afteraddputs the new note in the array, write the whole array back tonotes.jsonas 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. - In
notes.js, in theaddbranch, replace the line that printsAdding: .... It now prints onlySaved note, the new note's number, and a full stop. With the two notesnotes.jsonstarts with,node notes.js add Buy breadprints:andSaved note 3.notes.jsonthen holds:[ "Buy milk", "Call Ada", "Buy bread" ] - When there is no
notes.json,addcreates it. Afterclear,node notes.js add Call AdaprintsSaved note 1., andlistthen shows1. 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
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommandsPractice on your own: Express playground