Find OS username in NodeJS

2019-04-03 06:10发布

How would I find the username that the computer owner is using currently (while logged in), using NodeJS?

I have searched around a bit, but haven't found anything...

5条回答
冷血范
2楼-- · 2019-04-03 06:32

Definitely, the easiest way to do it is using username

Install:

$ npm install username

Then:

const username = require('username');

(async () => {
    console.log(await username());
    //=> 'current_username'
})();
查看更多
小情绪 Triste *
3楼-- · 2019-04-03 06:33

If you want to get information about the client witch call a route on your server, you have to parse client useragent.

https://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx

You can get client user agent with node using those examples :

How to handle user-agent in nodejs environment?

查看更多
Summer. ? 凉城
4楼-- · 2019-04-03 06:35

I am not sure why, but someone added an answer and then deleted it quickly after... I was fast enough to catch it though, and after checking, it is the shortest and most effective way of doing what I asked before:

require("os").userInfo().username

The only problem is, in Windows 10, it returns the first name of the owner account that has been used (just a heads up). Everything else works completely fine!

查看更多
趁早两清
5楼-- · 2019-04-03 06:35

If it doesn't need to be cross operating systems (just *nix based), one way you could do (keep in mind that exec could be potentially risky to use if you parameterize it):

const Promise = require( 'bluebird' ),
      exec    = Promise.promisify( require( 'child_process' ).exec );

exec( 'id -un' ).then( ( username )=> {
 // do something about it
});

If you want to use bluebird for promises, don't forget about: npm install bluebird --save

查看更多
We Are One
6楼-- · 2019-04-03 06:36

This one object you will get username:

let os = require('os')
console.log(os.userInfo());
查看更多
登录 后发表回答