0
0
NodejsHow-ToBeginner · 3 min read

How to Get Platform in Node.js: Simple Guide

In Node.js, you can get the current platform by using process.platform. This property returns a string like 'win32', 'linux', or 'darwin' that identifies the operating system platform.
📐

Syntax

The platform is accessed via the process.platform property in Node.js. It returns a string representing the operating system platform.

  • process: A global object in Node.js that provides information about the current Node.js process.
  • platform: A property of process that holds the platform name as a string.
javascript
process.platform
Output
'win32' // example output on Windows
💻

Example

This example shows how to print the current platform to the console. It demonstrates how to use process.platform to detect the operating system.

javascript
console.log('Current platform:', process.platform);
Output
Current platform: linux
⚠️

Common Pitfalls

Some common mistakes when getting the platform in Node.js include:

  • Trying to use navigator.platform which works in browsers but not in Node.js.
  • Assuming platform strings are the same across all systems; for example, macOS returns 'darwin', not 'mac'.
  • Not handling platform-specific code properly when writing cross-platform applications.
javascript
/* Wrong way (browser code, not Node.js) */
console.log(typeof navigator !== 'undefined' ? navigator.platform : undefined); // undefined in Node.js

/* Right way */
console.log(process.platform); // 'win32', 'linux', or 'darwin'
Output
undefined Current platform: linux
📊

Quick Reference

Common values returned by process.platform:

Platform StringOperating System
'win32'Windows
'linux'Linux
'darwin'macOS
'aix'IBM AIX
'freebsd'FreeBSD
'openbsd'OpenBSD
'sunos'SunOS
'android'Android

Key Takeaways

Use process.platform to get the current operating system platform in Node.js.
The value returned is a string like 'win32', 'linux', or 'darwin'.
Avoid using browser-specific properties like navigator.platform in Node.js.
Check platform strings carefully when writing cross-platform code.
process.platform is a simple and reliable way to detect the OS in Node.js.