[英](node.js) how to use environment variables in JSON file
我正在使用需要 JSON 配置文件的第 3 方庫,並且我需要將一些環境變量作為鍵值傳遞。 如果我像往常一樣包括它們,例如:
"s3": {
"key": process.env.AWS_ACCESS_KEY_ID,
"secret": process.env.AWS_SECRET_ACCESS_KEY,
"bucket": process.env.S3_MLL_BUCKET_NAME,
"destination": "/backups/database",
"encrypt": false,
"region": process.env.AWS_REGION
}
...我收到錯誤:
SyntaxError: config/s3_backup.config.json: Unexpected token p
JSON 沒有環境變量的概念。 您可以做的是將您的配置文件聲明為node.js
模塊,然后您將能夠使用您的環境變量,如下所示:
module.exports = {
s3: {
key: process.env.AWS_ACCESS_KEY_ID,
secret: process.env.AWS_SECRET_ACCESS_KEY,
bucket: process.env.S3_MLL_BUCKET_NAME,
destination: "/backups/database",
encrypt: false,
region: process.env.AWS_REGION
}
};
我遇到了同樣的問題,對我module.exports = {config: {"exampleAPIKey":"ruier4343"}}
是使用 js 文件並導出對象module.exports = {config: {"exampleAPIKey":"ruier4343"}}
...然后“字符串化”對象,然后將其解析回來到 json const config = require("./jsConfigs.js").config; const jsonConfig = JSON.parse(JSON.stringify(config))
const config = require("./jsConfigs.js").config; const jsonConfig = JSON.parse(JSON.stringify(config))
我嘗試了很多不同的方法,但這是唯一有效的方法。
我遇到了類似的問題,我必須在 config.json 中傳遞 Env 變量,而我的第 3 方系統主要接受 config.json。
這是對我有用的解決方法。
應用程序.js
//updating config.json to use environment variables during run time
const fs = require('fs');
const fileName = './public/config.json';
const file = require(fileName);
if (file && file.arguments && file.arguments.execute)
file.arguments.execute.url = process.env.executeUrl || "";
if (file && file.configurationArguments && file.configurationArguments.publish)
file.configurationArguments.publish.url = process.env.publishUrl || "";
fs.writeFile(fileName, JSON.stringify(file, null, 2), function writeJSON(err) {
if (err)
return console.log(err);
console.log('updated config.json');
});
http.createServer(app).listen(app.get('port'), function() {
console.log('App Express server listening on port ' + app.get('port'));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.