我正在尝试创建一个API调用来更改另一个文件(config.js)中的变量(在这种情况下为密码),并且我想永久更改“ mainpassword”的值(或者至少直到想要再次更改它),而不必执行复杂的fs.readFile并写废话。
设置config.mainpassword = "somethingelse"
不会修改config.js文件中的变量
index.js
//...expressjs and other stuff here
const config = require('./config.js');
app.post('/api/admin/changesitepassword', (req, res) => {
config.mainpassword = "fumo123"
const conffile = require('./config.js')
delete require.cache[require.resolve('./config.js')];
return res.send(`Changed password: ${config.mainpassword}\nconfig.js: ${conffile.mainpassword}`)
})
config.js
module.exports = {
//... other config info
mainpassword: 'fumo', // Password to lock behind
//... other config info
}
当我发布到它时,
Changed password: fumo123
config.js: fumo
它并没有改变
答案 0 :(得分:0)
您所能做的就是在配置更改时将配置保存在.json
文件中,并在启动应用程序时将其加载。
这不会监视文件的更改,因此,如果您手动更改文件中的密码,则必须重新启动服务器。
{ "mainpassword": "fumo123" }
// config.js
const fs = require('fs') // some minimal amount of "bullshit" is required
const config = require('./config.json')
config.set = (key, value, callback) => {
config[key] = value
fs.writeFile('./config.json', JSON.stringify(config), 'utf-8', callback)
}
module.exports = config
然后您可以使用set
方法来设置和保存更改
app.post('/api/admin/changesitepassword', (req, res, next) => {
// i'm assuming express is used here, so I pass the error to `next`
config.set('mainpassword', "fumo321", err => {
if (err) return next(err)
return res.send(`Changed password: ${config.mainpassword}`)
})
})
现在,每个导入配置的位置都会动态更新密码