【问题标题】:adding files to heroku app with a database addon in node.js使用 node.js 中的数据库插件将文件添加到 heroku 应用程序
【发布时间】:2021-10-03 12:15:49
【问题描述】:

我在 heroku 上托管我的 discord 机器人,我安装了这个数据库来添加文件,因为据我所知,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 很陌生,我并没有真正找到任何不和谐机器人的东西,我希望你能提供帮助。

【问题讨论】:

    标签: javascript node.js heroku discord.js


    【解决方案1】:

    PostgresSQL 是云 SQL 数据库。您使用 HTTP 请求与 API 对话以从数据库上传/下载文件/数据。

    PostgresSQL 有一个Node.js packagepg,用于与数据库交互。

    使用此数据库,您提供的代码可能如下所示:

    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 来使用此数据库,这可能是您所寻找的,也可能不是。

    【讨论】:

    • 还有其他更好用的数据库吗?我真的从来没有使用过一般的 sql 或数据库,所以我不太了解它,对不起,但如果 postgres 是我可以学习 sql 的最好的之一。无论如何考虑到我已经有一个用于机器人的客户端常量 const client = new Discord.Client(),我是否应该重命名 const { Client } = require("pg") 以免造成问题?当然有的话
    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2020-01-01
    相关资源
    最近更新 更多