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.
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.
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.
In currentPlatform we save the platform that we are using right now, so then we can match it against a given object with handlers.
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
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.
You can see the code in the repository.
Thank you very much for reading! If you have better ideas on how to write OS specific code, share them down below!
If you have any questions or comments feel free to put them in the comment section below or send me a message.
Check out my social media!