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 is a code sample for using the process.platform method:

      console.log(`Current platform: ${process.platform}`)

When you run that code, the string for your current operating system should be printed.

Build A Hacker News Clone
Learn how to build and deploy a full-stack, production-ready application with React.js, Node.js, and MongoDB.
View Course

Here are the possible values it can return:

  • "aix"
  • "darwin"
  • "freebsd"
  • "linux"
  • "openbsd"
  • "sunos"
  • "win32"

Alternatively, you can run the code with a require() like below:

      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!