9

As mentioned in https://stackoverflow.com/a/32556337/103396, require('os').homedir() is the way to get the user's home directory.

In Windows the desktop path would be on user_home_dir/Desktop:

require('path').join(require('os').homedir(), 'Desktop')

Will this work on other platforms?

Community
  • 1
  • 1
rtribaldos
  • 1,177
  • 14
  • 28

2 Answers2

2

Sorry for the late reply.

Yes, it does work cross-platform. So far, I've tested it on Windows 10 and Ubuntu, both have positive results.

See:

Windows 10 Screenshot

Ubuntu Screenshot

Etosticity
  • 217
  • 4
  • 14
  • This would definitely **NOT** work on localized Linux platforms. For instance, with the `it_IT` locale the desktop would be located in `$HOME/Scrivania`. – Andrea Lazzarotto Dec 15 '20 at 10:52
0

Works on macOS as well; in case it doesn't work with Desktop, you can of course fallback to homedir() base directory:

import { homedir } from 'os';
import { existsSync } from 'fs';
import { resolve } from 'path';

const getDesktopOrHomeDir = () => {
  const homeDir = resolve(homedir())
  const desktopDir = resolve(homedir(), 'Desktop')
  if (!existsSync(desktopDir)) {
    return homeDir;
  }
  return desktopDir;
}

writeFile(resolve(getDesktopOrHomeDir(), 'myfile.txt'), 'foobar')
kyr0
  • 341
  • 4
  • 6