'How to get OS username in NodeJS?
How would I get/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.
Solution 1:[1]
This one object you will get username:
let os = require('os')
console.log(os.userInfo());
Solution 2:[2]
process.env.USER Should work also at least in MAC or Linux. e.g.
let user = process.env.USER || ""
Solution 3:[3]
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'
})();
Solution 4:[4]
Dependency free method:
function getUsername() {
return (
process.env.SUDO_USER ||
process.env.C9_USER ||
process.env.LOGNAME ||
process.env.USER ||
process.env.LNAME ||
process.env.USERNAME
);
}
Solution 5:[5]
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
Solution 6:[6]
you can simply use
app.getPath('home')
It'll return the home path of the current user.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frankenmint |
| Solution 2 | Abu Shumon |
| Solution 3 | |
| Solution 4 | John Doherty |
| Solution 5 | Miroslav Saracevic |
| Solution 6 | Harsh Makwana |
