Node.jsで実行ファイルがあるディレクトリより上の階層にある.envを読み込む方法
October 14, 2020
Vueと.envを共有したくてこれ実装したけど結局無理… これDocker-Compose使えばええやんというお話
使うシーンはあるのか…?🤔
ex) Express.js
ディレクトリ構成
- ルートディレクトリ
- frontend/
- app.js
- hogehoge...
- .env
- .env.example
- .gitignore
- LICENSE
- README.md
app.js
import express from 'express'
import http from 'http'
import path from 'path'
import { fileURLToPath } from 'url'
import dotenv from 'dotenv'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
// 本リポジトリの最上位ディレクトリにある.envを読み込む
const ENV_PATH = path.join(__dirname, '../.env')
dotenv.config({ path: ENV_PATH })
const app = express()
const server = http.Server(app)
const PORT = process.env.BE_PORT || 7000
server.listen(PORT, () => {
console.log(`server listening. [http://localhost:${PORT}]`)
})