Skip to content

Commit

Permalink
Add .env file support
Browse files Browse the repository at this point in the history
  • Loading branch information
johtela committed Oct 31, 2024
1 parent 455193c commit 2615e12
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ backend
lib
testOut
dev.*
.env
30 changes: 30 additions & 0 deletions src/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
* [Express.js applications]: https://expressjs.com/en/5x/api.html#app
*/
//#region -c backend imports
import * as path from 'path'
import * as fs from 'fs'
import * as exp from 'express'
import * as cfg from './config'
import * as log from './logging'
//#endregion
/**
* ## Express Middleware
Expand Down Expand Up @@ -52,4 +56,30 @@ export function invalidateBackend() {
app = undefined
delete require.cache[bundle]
}
}
/**
* ## Read `.env` file
*
* If the root folder contains a file called `.env` load environment variables
* from it.
*/
const varDefRE = /^([A-Za-z]\w*)\s*\=\s*(.+)$/

export function loadEnvFile() {
let envpath = path.resolve(cfg.getOptions().baseDir, ".env")
if (fs.existsSync(envpath)) {
let content = fs.readFileSync(envpath, 'utf-8').split(/\r?\n/)
for (let i = 0; i < content.length; ++i) {
let line = content[i].trim()
if (line && !line.startsWith("#")) {
let match = line.match(varDefRE)
if (match)
process.env[match[1]] = match[2]
else {
log.warn("Invalid line skipped in .env file:\n" + line)
log.info("Correct format is <VARNAME>=<VARVALUE><newline>\n")
}
}
}
}
}
1 change: 1 addition & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export function start(opts: cfg.Options) {
})
}
app.use(exp.static(opts.outDir))
bak.loadEnvFile()
app.use(bak.backend)
app.get('/litscript', notifyHandler)
let { host, port } = opts.serveOptions
Expand Down

0 comments on commit 2615e12

Please sign in to comment.