One of the advantages of using Electron is that - since it’s cross-platform - we don’t have to worry about the operating system on which our application is going to be run.

However, sometimes we need our code to be OS-specific if, for example, we are going to be using command console or need to retrieve some information about the system.

Having to write multiple ifs each time we want to have some functionality on a given OS seems excess work and it quickly obfuscates the code rendering it difficult to be understood and analyzed.

In order to keep the code clean and readable, we can create a little helper and remove the ifs and any “OS-related” logic altogether.

Implementing Platforms

First, we see the platforms object which contains names of all supported operating systems. It is made only for convenience. We can then use platforms.WINDOWS instead of typing ‘WINDOWS’ each time into our object with handlers we pass to the byOS function.

Next, notice the platformsNames object, the keys of which are the result of calling os.platform(), and whose values are the keys from the platforms object. We simply map it to a more user-friendly name.

For example when os.platform() returns win32 we map it to platforms.WINDOWS by calling platformsNames[os.platform()].

In currentPlatform we save the platform that we are using right now, so then we can match it against a given object with handlers.

Implementing Releases

One might go even further and try to differentiate between releases of a given OS, for example, Windows 7, 8 and 10.

Now we can use os.release() to check for the system’s release.

We can split the resulting string and check the Windows version. A complete list can be found here. As for Linux/Mac, I didn’t really see how that could be useful, so I left it at releases.ANY.

In whatWindowsIsHeUsing you can see that we are only checking for different Windows’ releases if we are running the app on Windows.

You can see the code in the repository.

Thank you very much for reading!

Also available on FreeCodeCamp.