Skip to content

Instantly share code, notes, and snippets.

@matsumana
Last active June 22, 2021 02:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsumana/e3668baa6cebc662dd2e69ee34a61963 to your computer and use it in GitHub Desktop.
Save matsumana/e3668baa6cebc662dd2e69ee34a61963 to your computer and use it in GitHub Desktop.

サンプルソース

$ cat package.json
{
  "dependencies": {
    "config": "^3.3.6"
  }
}
$ cat config/default.json
{
    "url" : "https://example.com",
    "account" : {
         "name" : "foo",
         "pass" : "bar"
    }
}
$ cat config/custom-environment-variables.json
{
    "url" : "URL",
    "account" : {
         "name" : "ACCOUNT_NAME",
         "pass" : "ACCOUNT_PASS"
    },
    "hoge" : "HOGE"
}
$ cat index.js
const config = require('config');

const conf = config.get('hoge');
console.log(conf);



動作確認

HOGE環境変数から値を取得

hogeはdefault.jsonには未定義で、custom-environment-variables.jsonにのみ定義されているが、問題なく動く

$ HOGE=abc node ./index.js
abc

HOGE環境変数がない場合は例外が発生する

$ node ./index.js
/Users/matsumana/IdeaProjects/node-config_sandbox/node_modules/config/lib/config.js:182
    throw new Error('Configuration property "' + property + '" is not defined');
    ^

Error: Configuration property "hoge" is not defined
    at Config.get (/Users/matsumana/IdeaProjects/node-config_sandbox/node_modules/config/lib/config.js:182:11)
    at Object.<anonymous> (/Users/matsumana/IdeaProjects/node-config_sandbox/index.js:3:21)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Function.Module._load (node:internal/modules/cjs/loader:828:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment