Get current user windows MicrosoftAccount in node.js

Viewed 44

In a node.js cli app running on a windows machine, you can get the current local user using:

// method 1
const os = require('os')
console.log(os.userInfo())

// method 2
console.log(`${process.env.USERDOMAIN}\\${process.env.USERNAME}`)

Which outputs:

# METHOD 1
{
  uid: -1,
  gid: -1,
  username: 'adam',
  homedir: 'C:\\Users\\adam',
  shell: null
}

# METHOD 2
MYPC\adam

However, in modern Windows OS (e.g. Windows 10, 11), many users opt to sign-in with a Microsoft account. Apparently, this means there are 2 mirrored accounts on the machine:

  • {USERDOMAIN}\{USERNAME} where USERDOMAIN could be the local machine name or the enterprise network domain name
  • MicrosoftAccount\{EmailAddress} where EmailAddress is the Microsoft account username

How can I retrieve the 2nd variant of the username in node.js?

1 Answers

IMHO, you can use the windows registry hive HCU, which maps to the current user hive and find the data you need somewhere in the hive, though I don't know the exact path.

Alternatively, you could try running some PS1 script/command that will get this information for you, but this method cannot be reliable, since this option (running ps1) may be disabled on some machines by the user.

And last but not least, you can always build a native Node.js extension, using C++ and access the native Windows API to do what you want :)

Related