Detect the Current Operating System Platform Using NodeJS
Are you using Node.js and need to programmatically detect what operating system your code is running in?
Luckily, Node.js has an internal module called process that provides information and control over the current Node.js process. It's a global object, so it can be used anywhere inside a Node.js application. But, it can also be used by requiring it into your application as well:
const process = require("process")
Using that process module, we can get the current operating system with the process.platform property. When called, it returns a string for the operating system the Node.js process is currently running on.
Here are the possible values it can return:
  • "aix"
  • "darwin"
  • "freebsd"
  • "linux"
  • "openbsd"
  • "sunos"
  • "win32"
Here is a code sample for using the process.platform method:
Node.js
 
console.log(`Current platform: ${process.platform}`)
When you run that code, the string for your current operating system should be printed.
Alternatively, you can run the code with a require() like below:
Node.js
 
const process = require("process")
 
console.log(`Current platform: ${process.platform}`)
That should log the same result as the previous code example.
Hopefully, this was helpful in your coding endeavors.
Thanks for reading and happy coding!
Have any questions or comments about this article? You can contact me via email at nick@coderrocketfuel.com or on Twitter at @CoderRocketFuel.
If you enjoyed this free content, please consider supporting what I do by Buying Me a Coffee.