Modules in The Console – filesystem module as an example

This time I present a filesystem  module which mimics the simplest cases of shell commands: ls, pwd, cd, cat. The module showcases module commands, scoping, Storage and onload/onunload events.

Module definition

Rules are fairly simple here:

  1. onload()  is called every time when module is loaded or reloaded.
  2. onunload()  is called on every reload
  3. commands  is expected to be just an object where keys are commands that are going to be registered in every tab of The Console and values are functions to be called on command invoke

It’s worth noting that reload is automatically triggered when one of a module’s .js file is edited.

Let’s look at filesystem definition:

  1. In the beginning I import some Java classes.
  2. The scope is just my helper object, note that it is not required to have such.
  3. in onload  I save a “filesystem” global Storage that well be available not just to this module but also to all scripts on all tabs
  4. getCommands()  is a function because it can be laid after module.exports part, while variable declaring an object would have to be put before this part (it’s simply all about order of execution).


First, some helpers:

Now everything goes into function getCommands() { return { /* HERE!! */ } }  which is a function returning an object which will contain commands.

pwd – print current path

First, we make sure that user understands that this command does not receive any argument (parameter).

cd – change current path

This functions is a little more complicated. The algorithm takes this approach:

  1. check if given argument is a full path
  2. if the argument wasn’t a full path then try joining old path with the argument
  3. if anything up to this point is a valid path then remember it by invoking setCurrentPath(path)  helper

A little trick here is  file.getCanonicalPath() which helps with getting a path where real letter casing is used, e.g. if you were in C:/  and typed cd windows , then you expect to be in C:\Windows  rather than C:/windows .

ls – list files in current path

This command is simplier because when there is an argument then it’s assumed to be global. It could be improved to get a relative path as in cd  command.

cat – print contents of given file

Why having modular system?

The reasons behind modules were already described in previous posts. However, I’ll shortly summarize everything that looks like a benefit of having this system:

  • modules can be imported
  • modules can receive various events (even if right now there are only onload  and onunload )
  • a module can contain multiple commands
  • a module have custom scope that will live inside JS environment even after command finishes executing