Writing and Appending to Files

Your port reads and parses the week’s log. Dev’s Friday job also adds the week’s summary to season.txt, the history he forwards to Halden Heating, keeping every earlier week. Here’s how Python’s calls map to JavaScript. The file calls come from node:fs/promises, join() from node:path, and JSON is built in:

Python JavaScript
open(p, "a") and f.write(s) await appendFile(p, s)
open(p, "w") and f.write(s) await writeFile(p, s)
json.load(f) JSON.parse(await readFile(p, "utf8"))
json.dump(obj, f) await writeFile(p, JSON.stringify(obj))
Path(__file__).parent / "season.txt" join(import.meta.dirname, "season.txt")

Start with the call Dev needs every Friday.

Append the Week’s Summary

Before this run, the season file holds week 43:

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

Where Python uses a file object in a with block, JavaScript needs neither. appendFile() takes a path and the text, then opens, writes, and closes in one call. Like readFile(), it’s asynchronous, so you await it:

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"));

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.