Reading a Whole File
Dev’s port has the log’s name from the command line. Now it needs to read the log. In this lesson, you’ll read a whole file in JavaScript with one call, and find out what that call really hands back. Dev’s Python tool loops over the log line by line, but the port reads the whole text first. In Python, that’s f.read() inside a with block:
import sys
path = sys.argv[1]
with open(path, encoding="utf-8") as f:
text = f.read()
print(text)
lines = text.split("\n")
Run as python digest.py logs/week-44.log, it prints the ten readings of week 44, from Mon 07:00,71.5 to Fri 13:00,67.5.
Python’s open() is built in. In JavaScript, reading files comes from a module, node:fs/promises. The node: prefix marks one of Node’s own modules, so there’s nothing to install. One call, readFile(), takes the path and "utf8", where Python passes an encoding. There’s no file object and no with block: readFile() opens the file, reads it, and closes it for you. Here’s the line-by-line port. What does it log when it runs?