Inject variables from environment variables or js/json files to json


Keywords
environment-variables, injector, json, json-files
License
MIT
Install
npm install json-injector@0.5.0

Documentation

json-injector

Inject variables from environment variables or js/json files to json

Packages

Name Version Downloads
json-injector NPM version NPM Downloads
json-injector-cli NPM version NPM Downloads

install

  • npm
$ npm install json-injector
  • yarn
$ yarn add json-injector

How to use

1. Write template file(js or json)

module.exports = {
  testVar: '${testVar:-defaultValue}',
  home: '${home}',
  number: '123',
  a: {
    b: [0],
  },
};
  • You can write bash syntax to inject variables with inject-env.

2. Call json-injector API with injectors

  1. Passing options to jsonInjector
import jsonInjector from 'json-injector'
import envVarInjector from 'json-injector/lib/injectors/env-var'

jsonInjector({
  files: ['test'],
  injectors: [envVarInjector({ TEST_VAR: 'testVar', HOME: 'home' })],
  postInject: {
    number: v => +v,
    'a.b[0]': v => console.log(v),
  },
});
  1. Save options in config file.
const envVarInjector = require('json-injector/lib/injectors/env-var');

// test config
module.exports = {
  files: ['test'],      // files to be injected
  injectors: [          // injectors to be used
    envVarInjector({ TEST_VAR: 'testVar', HOME: 'home' })
  ],
  postInject: {         // post-inject action to each variable
    number: v => +v,
    'a.b[0]': v => console.log(v) || v,
  },
};
  • Injected json file will be saved as test.json
{
  "testVar": "defaultValue",
  "home": "/Users/kimxogus",
  "number": 123,
  "a": {
    "b": [
      0
    ]
  }
}

CLI App

Use json-injector-cli

Injectors

Environment Variable Injector

  • Resolves environment variable to user-named variable in string.
const envVarInjector = require('json-injector/lib/injectors/env-var');

envVarInjector({
  TEST_VAR:       // key: Environment Variable name.
    'testVar'     // value: Variable name to be injected in json.
});

File Injector

  • Reads js or json files and inject their variables.
const fileInjector = require('json-injector/lib/injectors/file');

const testConfigPath = process.env.HOME + '/test';

fileInjector({
  baseDir: testConfigPath,                    // base directory
  patterns: ['config/*.json', 'config/*.js'], // file's patterns (relative to baseDir)
});