Importing From Your Own Files
Dev keeps the parsing in readings.py so Asha can reuse it, and digest.py imports three
functions from it in one line, from readings import is_blank, parse_line, summarise. Does that
line still work in JavaScript?
Unlike a Python file, a JavaScript file shares only what it marks with export: so far, only
parseLine() in readings.js (its body is folded here, as in the video):
readings.js
export function parseLine(line) {
…
}
The package.json beside the files holds { "type": "module" }, so Node treats every .js file
in the folder as a module.
First step: both digest files import the parser and parse Thursday’s 07:00 reading, the week’s
peak. In Python, that’s from readings import parse_line. The JavaScript line swaps Python’s two
words: import first, then the name you take, in braces, spelled as readings.js exports it.
The braces aren’t an object. Then comes from, and the source, a string in quotes.
Watch out: if the line starts with from, as Python’s does, it stops with a SyntaxError.
Names first, source last. With the other two lines ported line for line, here’s the port:
digest.js
import { parseLine } from "readings";
const reading = parseLine("Thu 07:00,78.0");
console.log(reading);
In Python, the bare name finds readings.py next door. Running this with node digest.js stops
with an error, and the reading never prints. In your terminal, Node prints its own lines around
the error, so read the line that starts with Error. Here it is, the folder part shortened:
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'readings' imported from .../boiler-digest/digest.js
A bare name such as "readings" means a package: installed code, like pip’s, named without a
path. So Node never looks for a readings file next to digest.js, only among installed
packages. In JavaScript, the spelling picks package or file: your own file is always a path.
Add ./, for next to digest.js itself, wherever you run it from, and the error changes to
Cannot find module '.../readings'. It says module, not package, so ./ worked. Now Node looks
for a file called readings, with no extension, and there isn’t one. The next line suggests the
fix: Did you mean to import "./readings.js"?
Unlike Python’s import, Node adds no extension: like a path in Python’s open(), an import path
names exactly one file, though it counts from this file, not from where you run it. Copied an
import without the extension? Add the one the Did you mean line suggests:
digest.js
import { parseLine } from "./readings.js";
const reading = parseLine("Thu 07:00,78.0");
console.log(reading);
Run it with node digest.js once more, and Thursday’s reading logs:
{ time: 'Thu 07:00', temp: 78 }
That’s the JavaScript way: a bare name is a package, and your own file is a path, with ./ for
“next to this file” and the full file name, .js included.
Next up: Choosing What a Module Shares, a text lesson, where you’ll export the rest of
readings.js and import several names in one pair of braces.