Node.Js - Get windows username

Someone has created a module called username that does all of the hard work for you.

You use it like

var username = require('username');

console.log( username.sync() );

I understand that this will not give the client user of a web app as OP asked, but this question is very high in the search results for trying to get the logged in user when running a Node application locally.

You can reproduce the <domain>\<username> output of whoamI and WindowsIdentity.GetCurrent() with environment variables in Windows.

process.env.USERDOMAIN + '\\' + process.env.USERNAME

If you'd rather use USERPROFILE:

process.env.USERDOMAIN + '\\' + process.env.USERPROFILE.split('\\').pop()


Since Node v6 (2016-04), you can just use os.userInfo :

var os = require('os');
os.userInfo().username

To get the current logged-in username:

var path = require('path');
var userName = process.env['USERPROFILE'].split(path.sep)[2];
var loginId = path.join("domainName",userName);
console.log(loginId);

Although node has the built in operating system function os and the os.hostname() to return the host name, you will need to access the client's hostname in ASP.NET or the language of your choice. You can't do that in node since it is running on the server side and has nothing to do with the client's local info.

> require('os')
> os.hostname()

Look at this question

Determine Client's Computer Name

GET CLIENT HOST NAME IN ASP.NET AKA CLIENT SIDE

System.Net.Dns.GetHostEntry( Request.ServerVariables["REMOTE_HOST"]).HostName;

SPOON FEED FOR THE LAZY

string IP = Request.UserHostName;
string compName = CompNameHelper.DetermineCompName(IP);

code from compnamehelper:

public static string DetermineCompName(string IP)
    {
        IPAddress myIP = IPAddress.Parse(IP);
        IPHostEntry GetIPHost = Dns.GetHostEntry(myIP);
        List<string> compName = GetIPHost.HostName.ToString().Split('.').ToList();
        return compName.First();
    }

MICROSOFT DOCUMENTATION