Reputation: 5361
I'm using a 3rd party library that needs a JSON config file, and I need to pass some env variables in as key values. If I include them as I normally would, eg:
"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
}
...I get the error:
SyntaxError: config/s3_backup.config.json: Unexpected token p
Upvotes: 46
Views: 125542
Reputation: 480
What worked for me was using a js file and exporting an object:
module.exports = {config: {"exampleAPIKey":"ruier4343"}}
Then I stringified the object and then parsed it back to json:
const config = require("./jsConfigs.js").config;
const jsonConfig = JSON.parse(JSON.stringify(config));
Upvotes: 8
Reputation: 143
I faced similar issue where i have to pass Env variables inside config.json and my 3rd party system accepts mainly config.json.
Here is the workaround that worked for me.
App.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'));
});
Upvotes: 4
Reputation: 1884
JSON does not have notion of environment variables. What you can do though is to declare your configuration file as node.js
module and then you will be able to use your environment variables as follows:
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
}
};
Upvotes: 45