├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.d.ts ├── index.js ├── index.test-d.ts ├── license ├── package.json ├── readme.md ├── test-fallback.js ├── test-userinfo.js └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | Get the username of the current user. 3 | 4 | It first tries to get the username from the `SUDO_USER` `LOGNAME` `USER` `LNAME` `USERNAME` environment variables. Then falls back to `$ id -un` on macOS / Linux and `$ whoami` on Windows, in the rare case none of the environment variables are set. The result is cached. 5 | 6 | @returns The username. 7 | 8 | @example 9 | ``` 10 | import {username} from 'username'; 11 | 12 | console.log(await username()); 13 | //=> 'sindresorhus' 14 | ``` 15 | */ 16 | export function username(): Promise; 17 | 18 | /** 19 | Synchronously get the username of the current user. 20 | 21 | It first tries to get the username from the `SUDO_USER` `LOGNAME` `USER` `LNAME` `USERNAME` environment variables. Then falls back to `$ id -un` on macOS / Linux and `$ whoami` on Windows, in the rare case none of the environment variables are set. The result is cached. 22 | 23 | @returns The username. 24 | 25 | @example 26 | ``` 27 | import {usernameSync} from 'username'; 28 | 29 | console.log(usernameSync()); 30 | //=> 'sindresorhus' 31 | ``` 32 | */ 33 | export function usernameSync(): string | undefined; 34 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import os from 'node:os'; 3 | import {execa, execaSync} from 'execa'; 4 | import memoize from 'memoize'; 5 | 6 | const getEnvironmentVariable = () => { 7 | const {env} = process; 8 | 9 | return ( 10 | env.SUDO_USER 11 | || env.C9_USER // Cloud9 12 | || env.LOGNAME 13 | || env.USER 14 | || env.LNAME 15 | || env.USERNAME 16 | ); 17 | }; 18 | 19 | const getUsernameFromOsUserInfo = () => { 20 | try { 21 | return os.userInfo().username; 22 | } catch {} 23 | }; 24 | 25 | const cleanWindowsCommand = string => string.replace(/^.*\\/, ''); 26 | 27 | const makeUsernameFromId = userId => `no-username-${userId}`; 28 | 29 | export const username = memoize(async () => { 30 | const environmentVariable = getEnvironmentVariable(); 31 | if (environmentVariable) { 32 | return environmentVariable; 33 | } 34 | 35 | const userInfoUsername = getUsernameFromOsUserInfo(); 36 | if (userInfoUsername) { 37 | return userInfoUsername; 38 | } 39 | 40 | /** 41 | First we try to get the ID of the user and then the actual username. We do this because in `docker run --user :` context, we don't have "username" available. Therefore, we have a fallback to `makeUsernameFromId` for such scenario. Applies also to the `sync()` method below. 42 | */ 43 | try { 44 | if (process.platform === 'win32') { 45 | const {stdout} = await execa('whoami'); 46 | return cleanWindowsCommand(stdout); 47 | } 48 | 49 | const {stdout: userId} = await execa('id', ['-u']); 50 | try { 51 | const {stdout} = await execa('id', ['-un', userId]); 52 | return stdout; 53 | } catch {} 54 | 55 | return makeUsernameFromId(userId); 56 | } catch {} 57 | }); 58 | 59 | export const usernameSync = memoize(() => { 60 | const envVariable = getEnvironmentVariable(); 61 | if (envVariable) { 62 | return envVariable; 63 | } 64 | 65 | const userInfoUsername = getUsernameFromOsUserInfo(); 66 | if (userInfoUsername) { 67 | return userInfoUsername; 68 | } 69 | 70 | try { 71 | if (process.platform === 'win32') { 72 | return cleanWindowsCommand(execaSync('whoami').stdout); 73 | } 74 | 75 | const {stdout: userId} = execaSync('id', ['-u']); 76 | try { 77 | return execaSync('id', ['-un', userId]).stdout; 78 | } catch {} 79 | 80 | return makeUsernameFromId(userId); 81 | } catch {} 82 | }); 83 | -------------------------------------------------------------------------------- /index.test-d.ts: -------------------------------------------------------------------------------- 1 | import {expectType} from 'tsd'; 2 | import {username, usernameSync} from './index.js'; 3 | 4 | expectType>(username()); 5 | expectType(usernameSync()); 6 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "username", 3 | "version": "7.0.0", 4 | "description": "Get the username of the current user", 5 | "license": "MIT", 6 | "repository": "sindresorhus/username", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": { 15 | "types": "./index.d.ts", 16 | "default": "./index.js" 17 | }, 18 | "sideEffects": false, 19 | "engines": { 20 | "node": ">=18" 21 | }, 22 | "scripts": { 23 | "test": "xo && ava && tsd" 24 | }, 25 | "files": [ 26 | "index.js", 27 | "index.d.ts" 28 | ], 29 | "keywords": [ 30 | "username", 31 | "user", 32 | "login", 33 | "name", 34 | "logname", 35 | "lname", 36 | "whoami", 37 | "shell", 38 | "env", 39 | "environment", 40 | "variable" 41 | ], 42 | "dependencies": { 43 | "execa": "^8.0.1", 44 | "memoize": "^10.0.0" 45 | }, 46 | "devDependencies": { 47 | "ava": "^5.3.1", 48 | "tsd": "^0.29.0", 49 | "xo": "^0.56.0" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # username 2 | 3 | > Get the username of the current user 4 | 5 | This module is meant for informational purposes and not for secure identification. 6 | 7 | ## Install 8 | 9 | ```sh 10 | npm install username 11 | ``` 12 | 13 | *This package only works in Node.js, not in browsers.* 14 | 15 | ## Usage 16 | 17 | ```js 18 | import {username} from 'username'; 19 | 20 | console.log(await username()); 21 | //=> 'sindresorhus' 22 | ``` 23 | 24 | ## API 25 | 26 | It first tries to get the username from the `SUDO_USER` `LOGNAME` `USER` `LNAME` `USERNAME` environment variables. Then falls back to `$ id -un` on macOS / Linux and `$ whoami` on Windows, in the rare case none of the environment variables are set. The result is cached. 27 | 28 | ### `username(): Promise` 29 | 30 | Returns the username. 31 | 32 | ### `usernameSync(): string | undefined` 33 | 34 | Returns the username. 35 | 36 | ## Related 37 | 38 | - [username-cli](https://github.com/sindresorhus/username-cli) - CLI for this module 39 | - [fullname](https://github.com/sindresorhus/fullname) - Get the fullname of the current user 40 | -------------------------------------------------------------------------------- /test-fallback.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import os from 'node:os'; 3 | import test from 'ava'; 4 | import {username, usernameSync} from './index.js'; 5 | 6 | // Remove `os.userInfo()` and reset ENV flags to avoid them taking precedence 7 | delete os.userInfo; 8 | process.env.LOGNAME = ''; 9 | process.env.USER = ''; 10 | process.env.LNAME = ''; 11 | process.env.USERNAME = ''; 12 | 13 | test('async', async t => { 14 | const username_ = await username(); 15 | t.true(username_?.length > 1); 16 | }); 17 | 18 | test('sync', t => { 19 | t.true(usernameSync()?.length > 1); 20 | }); 21 | -------------------------------------------------------------------------------- /test-userinfo.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import os from 'node:os'; 3 | import test from 'ava'; 4 | import {username, usernameSync} from './index.js'; 5 | 6 | process.env.LOGNAME = ''; 7 | process.env.USER = ''; 8 | process.env.LNAME = ''; 9 | process.env.USERNAME = ''; 10 | 11 | test.serial('username()', async t => { 12 | os.userInfo = () => ({username: 'unicorn'}); 13 | t.is(await username(), 'unicorn'); 14 | }); 15 | 16 | test.serial('username.sync()', t => { 17 | os.userInfo = () => ({username: 'unicorn2'}); 18 | t.is(usernameSync(), 'unicorn2'); 19 | }); 20 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import process from 'node:process'; 2 | import test from 'ava'; 3 | import {username, usernameSync} from './index.js'; 4 | 5 | test.serial('username()', async t => { 6 | process.env.LOGNAME = 'unicorn'; 7 | t.is(await username(), 'unicorn'); 8 | }); 9 | 10 | test.serial('username.sync()', t => { 11 | process.env.LOGNAME = 'unicorn2'; 12 | t.is(usernameSync(), 'unicorn2'); 13 | }); 14 | --------------------------------------------------------------------------------