Running a Module as a Script

Your port now has two files that fit together: readings.js exports the parsing functions, and digest.js imports them. Where Dev runs python digest.py, you start the port with node digest.js, since node runs a file as python does.

Both Python files end with a main guard, though, and that guard has no JavaScript form you can copy. You’ll see why the port mostly doesn’t need it, and what the one file that does should write.

Let the Entry File Do the Work

The Python tool is already split the way JavaScript programs are: readings.py is a module, and digest.py is the file Dev runs. Even so, digest.py keeps its work in main() and ends like this:

Language: Python
from readings import is_blank, parse_line, summarise

def main():
    ...

if __name__ == "__main__":
    main()

Python convention guards even the file you run, so a test or another tool can import it without starting the program. Watch out if you port that line as is: if (__name__ === "__main__") stops with ReferenceError: __name__ is not defined, because JavaScript has no __name__ variable, and reading an undeclared name throws.

JavaScript convention makes the guard unnecessary. Most modules only export functions, so importing them does nothing visible. The entry file is the one you hand to node. Anything worth importing or testing lives in a module like readings.js, so nothing ever imports the entry file, and its top level is the program. The port drops both main() and the guard.

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.