Node.js - Find home directory in platform agnostic way

node.jsFilesystemsPlatform IndependentHome DirectoryPlatform Agnostic

node.js Problem Overview


Process.platform returns "win32" for Windows. On Windows a user's home directory might be C:\Users[USERNAME] or C:\Documents and Settings[USERNAME] depending on which version of Windows is being used. On Unix this isn't an issue.

node.js Solutions


Solution 1 - node.js

As mentioned in a more recent answer, the preferred way is now simply:

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

[Original Answer]: Why not use the USERPROFILE environment variable on win32?

function getUserHome() {
  return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}

Solution 2 - node.js

os.homedir() was added by this PR and is part of the public 4.0.0 release of nodejs.


Example usage:

const os = require('os');

console.log(os.homedir());

Solution 3 - node.js

Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.

function getUserHome() {
  return process.env.HOME || process.env.USERPROFILE;
}

EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()).

Solution 4 - node.js

Use osenv.home(). It's maintained by isaacs and I believe is used by npm itself.

https://github.com/isaacs/osenv

Solution 5 - node.js

getUserRootFolder() {
  return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}

Solution 6 - node.js

in some cases try to use this:

this.process.env.USERPROFILE

or

this.nw.process.env.USERPROFILE

i.e. add this or this.nw before process

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthewView Question on Stackoverflow
Solution 1 - node.jsmaericsView Answer on Stackoverflow
Solution 2 - node.jsCody Allan TaylorView Answer on Stackoverflow
Solution 3 - node.jsOncle TomView Answer on Stackoverflow
Solution 4 - node.jsAndrew De AndradeView Answer on Stackoverflow
Solution 5 - node.jsaH6yView Answer on Stackoverflow
Solution 6 - node.jsMaxProfit GlobalView Answer on Stackoverflow