问题
I have a on-cloud SAAS application built on Angular/NodeJS/Postgres+MongoDB stack that can connect to customer DB, cloud warehouses, S3 buckets etc to load information. Once I get the connection information from Angular front-end I need to store this information for future retrieval .
Example :
Angular Front-end
<form>
Database Type :
Host :
Port :
Username:
Password :
S3Bucket :
Region :
bucket-name :
Access key :
</form>
etc.
I need this information saved for later access. As suggested by Abdullah Deliogullari in the original question, I am trying to use config module npm config. But how do I use package config to write config file and load it in a running application.
ie While my application is running I need to write the (say S3) bucket info to a customer.config file (from frontend JSON) and later when required to retrieve data use the customer.config to connect to S3 bucket.
The "get" portion I am able to understand but the write portion (adding a new section dynamically) is what I am not able to figure out.
Example from frontend when I pass in the values like
["ct_postgres":
{"host":"3.15.xxx.xxx",
"port":"5132",
"dbname":"wcdb"
}]
this should be written to the config file. So something like config.put/write I am looking for. Next time I want to make connection to the customer postgresdb I do config.get() and it provides me the connection details.
Original question
回答1:
First you should install this package
npm install config
After that create config file into your project directory(name "config" is a must). In this file create development.json and production.json files(these names are optional). Content of development.json could be like this
{
"SERVER" : {
"port" : 5000
},
"PASSWORDHASH" : {
"saltRounds" : 10
}
}
In your javascript file for example in app.js file, first you should include the library, and then you can get configuration informations via this module
const config = require('config');
const port = config.get("SERVER.port");
app.listen(port);
Last step should be add this development.json file name to NODE_ENV variable
NODE_ENV=development node app.js
So if you want to update your json file based on new data coming from your frontend, you can basically do this
var fs = require('fs');
var file_content = fs.readFileSync("development.json");
var content = JSON.parse(file_content);
content.SERVER.port = 6000;
fs.writeFileSync("development.json", JSON.stringify(content));
来源:https://stackoverflow.com/questions/64781386/config-file-in-nodejs-using-npm-config