Close your program and everything it knew is gone: every variable, every score, every list. Memory is a whiteboard, wiped the moment the program ends. A file is a notebook on the shelf. Every program that remembers does the same three things: read the file into memory at the start, work in memory while it runs, write it back before it ends.
In Node the tools ship with the node:fs module. writeFileSync(file, text) creates the file, or replaces its whole content if it exists; it never appends. readFileSync(file, "utf8") reads it back, and the "utf8" matters: without it you get a Buffer of raw bytes instead of a string. To add a line you read the old text, glue the new line on, and write everything back.
Real data is objects, not text, which is what JSON is for. JSON.stringify(obj, null, 2) packs an object into readable text and JSON.parse(text) rebuilds it. The catch is what JSON cannot hold. It keeps objects, arrays, strings, numbers, booleans and null. Functions and undefined values are dropped without an error, a Date becomes a string, and a Map or Set becomes empty braces.
Put it together and you get the shape of every save tool: load, change, save. A notes tool is under 30 lines: process.argv[2] holds the command (your own words start at index 2, since 0 and 1 are Node and the script), load() wraps JSON.parse(readFileSync(...)) in try and catch and returns an empty array on the first run, and add writes the array back with JSON.stringify(notes, null, 2).
Video walkthrough: https://youtu.be/9Llr0WvUSs8
Full article: https://codesarray.com/articles/javascript/beginner/files-and-json/
Top comments (0)