-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import * as fs from 'node:fs' | ||
|
||
function parseEnvFile(contents) { | ||
return contents.split('\n').reduce((acc, line) => { | ||
const [key, value] = line.split('=') | ||
if (key) { // 确保键存在,即使值为空 | ||
acc.set(key.trim(), value === undefined ? '' : value.trim()) | ||
} | ||
return acc | ||
}, new Map()) | ||
} | ||
|
||
function updateEnvironmentFile() { | ||
const examplePath = '.env.example' | ||
const envPath = '.env' | ||
|
||
const exampleContents = fs.readFileSync(examplePath, 'utf-8') | ||
const envContents = fs.existsSync(envPath) ? fs.readFileSync(envPath, 'utf-8') : '' | ||
|
||
const exampleConfig = parseEnvFile(exampleContents) | ||
const envConfig = parseEnvFile(envContents) | ||
|
||
// 兼容 key 存在但 value 为空的情况 | ||
exampleConfig.forEach((value, key) => { | ||
if (!envConfig.has(key)) { // 如果 .env 中没有该 key | ||
envConfig.set(key, value) // 添加 key,即使其 value 为空 | ||
} | ||
}) | ||
|
||
// 生成新的 .env 内容 | ||
const newEnvContents = Array.from(envConfig.entries()) | ||
.map(([key, value]) => `${key}=${value}`) | ||
.join('\n') | ||
|
||
fs.writeFileSync(envPath, newEnvContents) | ||
console.log('.env file has been updated') | ||
} | ||
|
||
updateEnvironmentFile() |