Course contentsShow
← JavaScript
Lesson 1538 of 2,72333. JavaScript in Node.jsFree lesson

Working with os.homedir(), os.tmpdir(), and EOL

Getting user home directory, temp directory paths, and platform-specific end-of-line characters with os module.

Working with os.homedir(), os.tmpdir(), and EOL

You'll learn how to locate the user's home directory, find the system's temporary folder, and handle line breaks correctly across different operating systems.

Why These Matter

When writing Node.js applications, you often need to store user-specific files, create temporary data, or write text files. Where should these files go? The answer differs between Windows, macOS, and Linux. The os module provides platform-independent ways to find these common paths.

The Three Key Helpers

os.homedir() returns the current user's home directory path. On macOS/Linux, this might be /Users/john or /home/john. On Windows, it's typically C:\Users\John. This is perfect for storing user preferences or application data.

os.tmpdir() gives you the system's designated temporary directory. Your app can safely create temporary files here that the OS may eventually clean up. Think of it as a scratch pad provided by the operating system.

os.EOL (End-Of-Line) is a string constant containing the platform's line break character(s). Windows uses \r\n (carriage return + line feed), while Unix-based systems use just \n. Using os.EOL ensures your text files format correctly on any platform.

const os = require('os');

// Get user's home directory
console.log('Home:', os.homedir());

// Get temporary directory
console.log('Temp:', os.tmpdir());

// Get platform-specific line ending
console.log('EOL:', JSON.stringify(os.EOL));

// Writing cross-platform text
const text = `First line${os.EOL}Second line${os.EOL}Third line`;

Key Takeaway: Use os.homedir() for user-specific paths, os.tmpdir() for temporary files, and os.EOL for correct line breaks — they handle platform differences automatically so your code works everywhere.