Finding Files Next to a Module

Dev’s digest needs the names, log files, and temperature limits for all three heating plants. That list belongs to the tool, in boiler/plants.json. Running the digest from another folder mustn’t make it look for a different plant list. You’ll keep that connection to the module, then replace the file-reading code with a JSON import.

Find the Module’s Neighbors

In Python, settings.py builds the plant file’s path from its own __file__, so the shell’s current folder doesn’t decide which file it opens:

Language: Python
import json
from pathlib import Path

PLANTS_FILE = Path(__file__).with_name("plants.json")

def load_plants():
    return json.loads(PLANTS_FILE.read_text(encoding="utf-8"))

JavaScript’s import.meta.dirname supplies the module’s own folder as an absolute path. The join() function from node:path combines path pieces using your system’s separators, like Python’s os.path.join(). The resulting path is a plain string, rather than a Path object.

For the following examples, work inside ~/boiler-digest/boiler, with "type": "module" in the project’s package.json so .js files run as modules. Keep this shared plant list in plants.json:

Language: JSON Filename: plants.json
[
  {
    "name": "Main boiler", "log": "main.log",
    "controller": "halden", "limit": 75
  },
  {
    "name": "Sports hall", "log": "sports-hall.log",
    "controller": "halden", "limit": 80
  },
  {
    "name": "Science block", "log": "science.log",
    "controller": "ostra", "limit": 55
  }
]

The JavaScript port reads the file with readFile() from the built-in node:fs/promises module. await waits for the result, "utf8" requests decoded text, and JSON.parse() turns it into a JavaScript value. The braces in a named import select exported functions, and const binds a name that won’t be reassigned. Update the plant-loading portion of settings.js as shown, keeping its other exports, including verbose, which readings.js imports:

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.