config-helper.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const fs = require('fs');
  2. class ConfigLoader {
  3. data = {};
  4. add(values) {
  5. Object.assign(this.data, values);
  6. return this;
  7. }
  8. env() {
  9. return this.add(process.env);
  10. }
  11. envFile(filepath = '.env') {
  12. let content = '';
  13. try {
  14. content = fs.readFileSync(filepath, 'utf8');
  15. } catch {
  16. // ignore error
  17. }
  18. const values = content
  19. .split('\n')
  20. .map((line) => line.trim())
  21. .filter((line) => line && !line.startsWith('#'))
  22. .map((line) => {
  23. const i = line.indexOf('=');
  24. if (i < 0) return [];
  25. const key = line.split(0, i).trim();
  26. let value = line.split(i + 1).trim();
  27. // Note: escaped characters are not supported
  28. if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
  29. return [key, value];
  30. })
  31. .reduce((prev, [key, value]) => {
  32. if (key) prev[key] = value;
  33. return prev;
  34. }, {});
  35. return this.add(values);
  36. }
  37. get(key, def) {
  38. return this.data[key] ?? def;
  39. }
  40. }
  41. exports.ConfigLoader = ConfigLoader;
  42. exports.configLoader = new ConfigLoader();