Skip to content

Commit 2018c2b

Browse files
author
Syncher Pylon, Peng
committed
feat: support to parse home directory
1 parent 3214bf4 commit 2018c2b

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

lib/main.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type DotenvConfigOutput = {
2323

2424
const fs = require('fs')
2525
const path = require('path')
26+
const os = require('os')
2627

2728
function log (message /*: string */) {
2829
console.log(`[dotenv][DEBUG] ${message}`)
@@ -73,6 +74,10 @@ function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */)
7374
return obj
7475
}
7576

77+
function resolveHome(envPath) {
78+
return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
79+
}
80+
7681
// Populates process.env from .env file
7782
function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
7883
let dotenvPath = path.resolve(process.cwd(), '.env')
@@ -81,7 +86,7 @@ function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */
8186

8287
if (options) {
8388
if (options.path != null) {
84-
dotenvPath = options.path
89+
dotenvPath = resolveHome(options.path)
8590
}
8691
if (options.encoding != null) {
8792
encoding = options.encoding

package.json

-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
"dtslint": "dtslint types",
1515
"lint": "standard",
1616
"postlint": "standard-markdown",
17-
"pretest": "npm run lint && npm run dtslint",
1817
"test": "tap tests/*.js --100",
1918
"prerelease": "npm test",
2019
"release": "standard-version"

tests/test-config.js

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
/* @flow */
22

33
const fs = require('fs')
4+
const os = require('os')
5+
const path = require('path')
46

57
const sinon = require('sinon')
68
const t = require('tap')
@@ -11,7 +13,7 @@ const mockParseResponse = { test: 'foo' }
1113
let readFileSyncStub
1214
let parseStub
1315

14-
t.plan(8)
16+
t.plan(9)
1517

1618
t.beforeEach(done => {
1719
readFileSyncStub = sinon.stub(fs, 'readFileSync').returns('test=foo')
@@ -34,6 +36,18 @@ t.test('takes option for path', ct => {
3436
ct.equal(readFileSyncStub.args[0][0], testPath)
3537
})
3638

39+
t.test('takes option for path along with home directory char ~', ct => {
40+
ct.plan(2)
41+
const mockedHomedir = '/Users/dummy'
42+
const homedirStub = sinon.stub(os, 'homedir').returns(mockedHomedir)
43+
const testPath = '~/.env'
44+
dotenv.config({ path: testPath })
45+
46+
ct.equal(readFileSyncStub.args[0][0], path.join(mockedHomedir, '.env'))
47+
ct.ok(homedirStub.called)
48+
homedirStub.restore()
49+
})
50+
3751
t.test('takes option for encoding', ct => {
3852
ct.plan(1)
3953

0 commit comments

Comments
 (0)