Skip to content

Commit

Permalink
fix(dotenv-flow:config): load the rest of .env* files even if `.env…
Browse files Browse the repository at this point in the history
…` doesn't exist

When `options.purge_dotenv` is set to `true` but the `.env` file doesn't exist, with this change "dotenv-flow" will keep loading the rest of the `.env*` files.

Closes #50.
  • Loading branch information
kerimdzhanov committed Aug 24, 2023
1 parent 1dbc701 commit 07502e3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
12 changes: 9 additions & 3 deletions lib/dotenv-flow.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,17 @@ function config(options = {}) {
silent = false
} = options;

try {
if (options.purge_dotenv) {
unload(resolve(path, '.env'), { encoding });
if (options.purge_dotenv) {
const dotenvFile = resolve(path, '.env');
try {
fs.existsSync(dotenvFile) && unload(dotenvFile, { encoding });
}
catch (error) {
return { error };
}
}

try {
const existingFiles = (
listFiles(path, { node_env })
.filter(filename => fs.existsSync(filename))
Expand Down
30 changes: 18 additions & 12 deletions test/unit/dotenv-flow-api.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -683,22 +683,28 @@ describe('dotenv-flow (API)', () => {
.that.equals('overwritten by the `.env.local`');
});

describe('and the `encoding` option is given', () => {
beforeEach('setup the `encoding` option', () => {
options.encoding = 'base64';
});
it('provides the `encoding` option if given', () => {
options.encoding = 'base64';

it('provides the given `encoding` to `fs.readFileSync` through `.unload`', () => {
$dotenvFiles['/path/to/project/.env'] = 'DEFAULT_ENV_VAR=ok';
$dotenvFiles['/path/to/project/.env'] = 'DEFAULT_ENV_VAR=ok';

dotenvFlow.config(options);
dotenvFlow.config(options);

expect($readFileSync.firstCall)
.to.have.been.calledWith(normalize('/path/to/project/.env'), { encoding: 'base64' });
expect($readFileSync.firstCall)
.to.have.been.calledWith(normalize('/path/to/project/.env'), { encoding: 'base64' });

expect($readFileSync.secondCall)
.to.have.been.calledWith(normalize('/path/to/project/.env'), { encoding: 'base64' });
});
expect($readFileSync.secondCall)
.to.have.been.calledWith(normalize('/path/to/project/.env'), { encoding: 'base64' });
});

it("loads the rest of `.env*` files even if `.env` file doesn't exist", () => {
delete $dotenvFiles['/path/to/project/.env'];

dotenvFlow.config(options);

expect(process.env)
.to.have.property('ENV_VAR')
.that.equals('overwritten by the `.env.local`');
});
});

Expand Down

0 comments on commit 07502e3

Please sign in to comment.