简体   繁体   中英

Node.js - How to find the desktop path?

As the mentioned Node.js - Find home directory in platform agnostic way question, we can find the home folder via this code:

const homedir = require('os').homedir();

But how can I find the desktop folder whatever language is it in Windows? Because in windows desktop folder name is differ to languages.

Actually, the name is always Desktop, regardless of language. However Windows creates a virtual alias for the folder. In Portuguese is "Área de Trabalho", but you can access with %USERPROFILE%\\Desktop

Try this

const homeDir = require('os').homedir();
const desktopDir = `${homedir}/Desktop`;
console.log(desktopDir);

It should work on Windows and MacOS.

NPM

With npm, try platform-folders

npm install platform-folders
import getPath from 'platform-folders';
console.log(getPath('downloads'));

Node

If you want to do it with raw node, the following works most of the time on all major platforms, but there are a few things to keep in mind:

It is does not have reliability equivalent to homedir() for these reasons:

  1. All platforms have a home directory, but not all platforms have a desktop, and not all desktops are also folders.
  2. homedir() will always point to the home folder even on future versions of a platform, but the code below will stop working on platforms that in future versions change where they put the default desktop.
  3. homedir() will work even if the user configures a home directory in a strange location, but if a user configures the desktop to be in an unusual location, the following does not work.
  4. This might fail to work on some platforms in some non-english locales, but in Windows, the desktop is accessible by "Desktop" in all languages.
const os = require('os');
const path = require('path');
const desktopDir = path.join(os.homedir(), "Desktop");
console.log(desktopDir);

Example Output:

C:\Users\jschmoe\Desktop
or
/home/jschmoe/Desktop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM