Writing and Appending to Files

Your port now reads the week’s log, splits it into lines, and turns each line into a reading. The report it prints is only half of Dev’s Friday job. The Python tool also adds a one-line summary to season.txt, the season’s history he forwards to Halden Heating, and that file has to keep every earlier week.

In this lesson, you’ll append to a file and write a whole one in JavaScript, read Halden Heating’s JSON limits, and keep the season file next to the script wherever Dev runs it.

Append the Week’s Summary

Python opens a file in append mode to add to its end. By the time it opens the file, digest.py has built the summary line, and it writes the line with its own newline:

Language: Python
summary = "logs/week-44.log: peak 78.0, 2 readings over 75.0"
with open("season.txt", "a") as f:
    f.write(summary + "\n")

Before this run, the season file holds the line for week 43:

Language: Text Filename: season.txt
logs/week-43.log: peak 74.5, 0 readings over 75.0

In JavaScript, you don’t need a file object. The node:fs/promises module that gave you readFile() also exports appendFile(), which takes a path and the text to add, then opens, writes, and closes in one call. Writing takes time, like reading, so you await it too. The try-out then reads the file back:

Language: JavaScript Filename: append-week.js
import { appendFile, readFile } from "node:fs/promises";

const summary = "logs/week-44.log: peak 78.0, 2 readings over 75.0";
await appendFile("season.txt", summary + "\n");

console.log(await readFile("season.txt", "utf8"));

Week 44 now sits under week 43:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.