Splitting a File Into Lines

Your port can now read the week’s log: await readFile("logs/week-44.log", "utf8") hands back the whole file as text. The Python tool, though, takes its readings one at a time, from Python’s most common file loop, for line in f:.

That loop is the next part to port, and porting it line by line has a catch. In this lesson, you’ll see why, split the text into lines yourself, and parse each line as digest.py does.

Count the Lines in the Week’s Log

Before the port parses anything, check that its loop sees the ten readings Dev expects. In Python, a counter does it:

Language: Python
count = 0
with open("logs/week-44.log", encoding="utf-8") as f:
    for line in f:
        count += 1
print(count)

Python prints 10. The JavaScript port has no with block, because readFile() opens, reads, and closes the file in one call, so a scratch script next to digest.js loops over the text it gets back:

Language: JavaScript Filename: count-lines.js
import { readFile } from "node:fs/promises";

const text = await readFile("logs/week-44.log", "utf8");

let count = 0;
for (const line of text) {
  count += 1;
}
console.log(count);

Predict the count before you run it with node count-lines.js in the boiler-digest/ folder. The script finishes without complaint and prints this:

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.