Writing JSON Text
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 13 of 33.
After changing an array, you can save it in a file. First turn the array back into JSON text with JSON.stringify. Then give that text to writeFileSync. Writing replaces the contents of the file.
const scores = [10, 20];
const text = JSON.stringify(scores);
writeFileSync('scores.json', text); // file contains [10,20]The file name chooses where to save. The second argument is the text to save. Reading and parsing that file later gives the array again. The provided import makes the file-writing function available.
Challenge
EasyRun executes node practice.js. The starter chooses two sample notes when no arguments are given, or uses the words you supply as notes.
Write the notes array to saved.json as JSON text. Keep the supplied read-back line. Run with no arguments: it prints ["Buy milk","Call Ada"]. Try arguments Read Walk: it prints ["Read","Walk"]. The number of notes may change.
Try it yourself
import { writeFileSync, readFileSync } from 'node:fs';
const notes = process.argv.length > 2 ? process.argv.slice(2) : ['Buy milk', 'Call Ada'];
writeFileSync('saved.json', '[]');
console.log(readFileSync('saved.json', 'utf8'));
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommands3Files
JSON Text and ValuesReading a FileWriting JSON TextWriting a FileRemoving a NotePractice on your own: Express playground