indexzero / nconf

Hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.
https://github.com/indexzero/nconf
MIT License
3.87k stars 255 forks source link

Does nconf work with multiple files? #422

Closed mstaicu closed 4 months ago

mstaicu commented 4 months ago

I have the following example

// server.js
import nconf from "nconf";

import { app } from "./app.js";

nconf.env({ lowerCase: true, parseValues: true, separator: "_" });
nconf.defaults({
  express: {
    port: 3000,
  },
});

This works, I get the correct value in nconf.get("express:port"), but if I do the same in app.js I get undefined. I tried this as well

// index.js
import nconf from "nconf";

nconf.env({ lowerCase: true, parseValues: true, separator: "_" });
nconf.defaults({
  express: {
    port: 3000,
  },
});

import "./server.js";

And I get undefined in server.js when running nconf.get("express:port")

mstaicu commented 4 months ago

It seems that this is not working because of how ES Modules are resolved in node.js

mstaicu commented 4 months ago

Guess what I'm trying to find out is, can I initialize nconf once and then use it in all ESM files without redoing the .env.argv.file?

mstaicu commented 4 months ago

Figured it out, I used dynamic ESM imports, now this works

import nconf from "nconf";

nconf.env({ lowerCase: true, parseValues: true, separator: "_" });

import('./server.js');
mhamann commented 4 months ago

Glad you figured it out! Thanks for posting your solution. I'm sure it'll be helpful to others as well.

mstaicu commented 4 months ago

Ended up with this file structure:

src
├── app.js
├── index.js
├── server.js
// server.js

import nconf from "nconf";

import { app } from "./app.js";

var port = nconf.get("AUTH_EXPRESS_PORT");

app.listen(port, () => console.log(`Listening on port ${port}`));
// index.js

import nconf from "nconf";

nconf.env();

import("./server.js");

Running the web app server via AUTH_EXPRESS_PORT=3000 node src/index.js, using that variable only for the current shell, or you can set it for current shell and all processes started from current shell by first doing export AUTH_EXPRESS_PORT=3000 and then running node src/index.js