Advertisement
Intermediate Node.js, Path & OS Modules

How would you use the node:os module to make a script's behavior adapt correctly across different operating systems?

Short answer

os.platform() (returning 'win32', 'darwin', 'linux', etc.) lets a script branch its logic for OS-specific behavior, such as choosing the correct command to open a file with the system's default application, locating platform-specific configuration directories, or adjusting file…

Save Node.js mock interview
Advertisement
AModel answer
os.platform() (returning 'win32', 'darwin', 'linux', etc.) lets a script branch its logic for OS-specific behavior, such as choosing the correct command to open a file with the system's default application, locating platform-specific configuration directories, or adjusting file path handling beyond what the path module alone addresses.
const os = require('node:os');

function getConfigDir() {
  switch (os.platform()) {
    case 'win32': return path.join(process.env.APPDATA, 'MyApp');
    case 'darwin': return path.join(os.homedir(), 'Library', 'Application Support', 'MyApp');
    default: return path.join(os.homedir(), '.config', 'myapp');
  }
}
Real-world example
A desktop-companion CLI tool determines the correct, OS-conventional location to store its configuration file by branching on os.platform(), storing it under %APPDATA% on Windows, ~/Library/Application Support on macOS, and ~/.config on Linux, matching each platform's own conventions rather than using a single hardcoded location everywhere.
Likely follow-ups
  • What other OS-specific conventions (besides config directories) commonly require this kind of platform branching in a cross-platform CLI tool?
  • How does os.platform() differ from process.platform, given both seem to report similar information?
Related topics