Heroku上的Node.js:prod上的PostgreSQL,dev上的SQLite3?(Node.js on Heroku: PostgreSQL on prod, SQLite3 on dev

编程入门 行业动态 更新时间:2024-10-27 18:33:06
Heroku上的Node.js:prod上的PostgreSQL,dev上的SQLite3?(Node.js on Heroku: PostgreSQL on prod, SQLite3 on dev?)

我有一个Node.js / Rails3应用程序,我在Heroku上托管。 当我在本地机器或远程生产盒上运行时,rails部分在PostgreSQL和SQLite3之间无缝切换。

在本地,rails框架连接到configite config/databases.yml定义的SQLite3,当我推送到Heorku时,部署脚本会用生产设置覆盖它。

我的node.js脚本没有Heroku可以挂钩的框架,并确保我在生产环境中使用正确的数据库。

如何让我的node.js脚本“正常工作”我的Rails应用程序在开发和生产环境之间无缝移动的方式?

I have a Node.js/Rails3 app that I'm hosting on Heroku. The rails portion seamlessly switches between PostgreSQL and SQLite3 when it's run on my local machine or the remote production box.

Locally, the rails framework connects to SQLite3 as defined in config/databases.yml and when I push to Heorku, the deploy scripts overwrite this with their production setup.

My node.js scripts don't have a framework that Heroku can hook into and make sure I'm using the right database in my production environment.

How can I make my node.js scripts "Just Work" the way my Rails app moves seamlessly between development and production environments?

最满意答案

Heroku公开了一个可以通过DATABASE_URL环境变量连接的数据库URL。 这是Heroku开发中心文档的相关部分。

使用Postgres数据库

要将PostgreSQL数据库添加到您的应用程序,请运行以下命令:

$ heroku addons:add shared-database

这将设置DATABASE_URL环境变量。 将postgres NPM模块添加到您的依赖项:

"dependencies": { ... "pg": "0.5.4" }

并使用该模块从代码中的某个位置连接到DATABASE_URL :

var pg = require('pg'); pg.connect(process.env.DATABASE_URL, function(err, client) { var query = client.query('SELECT * FROM your_table'); query.on('row', function(row) { console.log(JSON.stringify(row)); }); });

Heroku exposes a database URL you can connect to via the DATABASE_URL environment variable. Here's the relevant section from the Heroku Dev Center docs.

Using a Postgres Database

To add a PostgreSQL database to your app, run this command:

$ heroku addons:add shared-database

This sets the DATABASE_URL environment variable. Add the postgres NPM module to your dependencies:

"dependencies": { ... "pg": "0.5.4" }

And use the module to connect to DATABASE_URL from somewhere in your code:

var pg = require('pg'); pg.connect(process.env.DATABASE_URL, function(err, client) { var query = client.query('SELECT * FROM your_table'); query.on('row', function(row) { console.log(JSON.stringify(row)); }); });

更多推荐

本文发布于:2023-07-28 18:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:js   Node   Heroku   prod   dev

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!