NodeJS 如何从npm脚本动态编辑.env文件?

2fjabf4q  于 2022-12-12  发布在  Node.js
关注(0)|答案(1)|浏览(221)

我有一个.env文件,我正在处理一个项目,我不会透露整个文件,因为它包含敏感数据,但是,在该文件中,我有一个名为“STATUS”的项。
注意:这是一个不和谐的机器人,
“STATUS”变量如下所示:STATUS=DEVELOPMENT
在我的代码中,我有一个处理程序,它将命令部署到所有服务器或仅部署到与'STATUS'值相关的特定服务器。
示例:如果STATUS等于DEVELOPMENT,则它会将命令部署到开发服务器,如果它等于PRODUCTION,则它会将命令部署到bot所在的所有服务器。
代码如下所示:

if (STATUS == "DEVELOPMENT") {
  Routes.applicationGuildCommands(CLIENT_ID, process.env.DEVELOPMENT_GUILD_ID),
    { body: slashCommands },
    console.log(
      chalk.yellow(`Slash Commands • Registered Locally to 
  the development server`)
    );
} else if (STATUS == "PRODUCTION") {
  await rest.put(
    Routes.applicationCommands(CLIENT_ID),
    { body: slashCommands },
    console.log(chalk.yellow("Slash Commands • Registered Globally"))
  );
}

在我的package.json文件中,我希望有两个脚本来控制命令是被推送到生产还是开发。
例如:

"scripts": {
      "prod": "changes the 'STATUS' to 'PRODUCTION' and runs the file",
      "dev": "changes the 'STATUS' to 'DEVELOPMENT' and runs the file"
  },
brc7rcf0

brc7rcf01#

您可以创建一个简单的实用程序JS脚本来完成这项工作:

// status.js
const fs = require("fs")
const path = require("path")

// get the first argument passed to this file:
const status = process.argv[3] // the first and second element will always be `node` and `filename.js`, respectively

if(!status) {
  throw new Error("You must supply a status to change to")
}

const envPath = path.join(process.cwd(), ".env") // resolve to the directory calling this script
// parse the environment variable file
let env = fs.readFileSync(envPath)
env = env.split(/\r?\n/g) // optional linefeed character

let prevExists = false
for(let lineNumber in env) {
  if(env[lineNumber].startsWith("STATUS=")) {
    prevExists = true
    env[lineNumber] = `STATUS=${status}`
    break
  }
}
if(!prevExists) env.push(`STATUS=${status}`)

const newEnv = env.join("\n")
fs.writeFileSync(envPath, newEnv)

console.log(`Successfully changed the status to "${status}"`)

然后在你的package.json中,你可以把以下内容:

"scripts": {
  "prod": "node status.js PRODUCTION && command to deploy server",
  "dev": "node status.js DEVELOPMENT && command to deploy server"
}

相关问题