Sharing a Setting Between Modules

Dev’s digest now finds its plant list wherever you run it. The next connection is between the command line and the log reader: --verbose should make readings.js report skipped lines. You’ll keep one setting shared across the package and give the digest a way to change it.

A module runs once when first loaded. Python caches imported modules in sys.modules. JavaScript also reuses a loaded module. Importing the same settings module from the digest and the reader doesn’t create two independent settings. The difference is who can assign to the setting.

Change State Through Its Owner

In Python, the digest assigns a global through the module object. Here args holds the command-line arguments:

Language: Python
import sys
from boiler import settings

args = sys.argv[1:]
settings.verbose = "--verbose" in args

readings.py checks settings.verbose when it skips a line. Try the corresponding JavaScript assignment before changing the working digest. For these checks, work in ~/boiler-digest/boiler, keeping the project’s "type": "module". The existing verbose portion of settings.js is:

Language: JavaScript Filename: settings.js
export let verbose = false;

Keep its plant import, loadPlants(), and any other exports. The block shows only the setting. Save the following code as check-assignment.js alongside settings.js. import * as settings gives you the module’s namespace, and process.argv.slice(2) takes the arguments after the runtime and script names. The const declaration binds args to the argument array. .includes("--verbose") tests whether it contains the option:

Language: JavaScript Filename: check-assignment.js
import * as settings from "./settings.js";

const args = process.argv.slice(2);
settings.verbose = args.includes("--verbose");

Both node check-assignment.js --verbose and node check-assignment.js stop with this error. The location and stack are omitted here:

Language: Program Output
TypeError: Cannot assign to property 'verbose' of [object Module]
...

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.