[英]adding files to heroku app with a database addon in node.js
我在 heroku 上托管我的 discord bot,我安装了这个数据库来添加文件,因为据我所知,heroku 有一个临时文件系统,而且 fs 之类的东西也不再工作了。 这是我安装的插件: https : //elements.heroku.com/addons/heroku-postgresql
这是我用于附加到 txts/json 文件的代码示例:
// Json example
if (command === 'jsonExample') {
config.example = args[0]
var stringifiedConfig = JSON.stringify(config, null, 4);
fs.writeFileSync("./config.json", stringifiedConfig)
console.log(stringifiedConfig)
}
// Txt example
if (command === 'txtExample') {
fs.appendFileSync('folder/example.txt', data + "\r\n", (err) => {
if (err) throw (err)
})
}
console.log('File edited')
问题是我不知道如何调整它以与数据库一起工作,我对 heroku 很陌生,我真的没有找到任何关于不和谐机器人的东西,我希望你能帮忙。
PostgresSQL是一个云 SQL 数据库。 您使用 HTTP 请求与 API 通信以从数据库上传/下载文件/数据。
PostgresSQL 有一个Node.js 包pg
,您可以使用它与数据库进行交互。
使用此数据库,您提供的代码可能如下所示:
const { Client } = require("pg"),
client = new Client({
// make sure you set your environment variables in the heroku dashboard
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
});
client.connect();
async function commandCode(command, config, args, data) {
if (command === "jsonExample") {
config.example = args[0];
const stringifiedConfig = JSON.stringify(config);
await client.query(/* some SQL query here */);
console.log(stringifiedConfig);
} else if (command === "txtExample") {
await client.query(/* some SQL query here */);
console.log("File edited.");
}
}
您将需要知道如何使用 SQL 来使用此数据库,这可能是您正在寻找的,也可能不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.