Skip to content

Get a GitHub access token from either an environment variable or a file

License

Notifications You must be signed in to change notification settings

shinnn/load-gh-token

Repository files navigation

load-gh-token

npm version Build Status codecov

Get a GitHub access token from either an environment variable or a file

const loadGhToken = require('load-gh-token');

// When `process.env.GITHUB_TOKEN === '36fae5325faa9b32edfd776f6b85bf71ac0a49bf'`

(async () => {
  const token = await loadGhToken(); //=> '36fae5325faa9b32edfd776f6b85bf71ac0a49bf'
})();

Installation

Use npm.

npm install load-gh-token

API

const loadGhToken = require('load-gh-token');

loadGhToken([options])

options: Object
Return: Promise<string>

If there is an environment variable GITHUB_TOKEN, it reads its value.

If the variable GITHUB_TOKEN is not defined, then it reads a file github-token.txt at the current working directory.

// When `process.env.GITHUB_TOKEN` is undefined but a file ./github-token.txt exists

(async () => {
  const token = await loadGhToken();
  // '... contents of github-token.txt without whitespaces ...'
})();

If both the GITHUB_TOKEN environment variable and the file ./github-token.txt don't exist, the Promise will be rejected.

(async () => {
  try {
    await loadGhToken();
  } catch (err) {
    err.message;
    // Tried to get a personal access token for GitHub API from the `GITHUB_TOKEN` environment variable or a file at '/Users/example/github-token.txt', but neither exists.

    err.code;
    //=> 'ERR_NO_GITHUB_TOKEN'
  }
})();

License

ISC License © 2018 - 2019 Watanabe Shinnosuke