2017-09-30 184 views
0

我的文件DB/index.js我可以运行一个简单的命令来测试我是否可以使用node-postgres连接到PostgreSQL?

const { Pool } = require('pg'); 
const pool = new Pool; 

module.exports = { 
    query: (text, params, callback) => { 
     return pool.query(text,params,callback); 
    } 
}; 

在我的主文件main.js我做的:

const db = require('./db/index'); 
我可以在数据库运行

什么命令弄清楚,如果节点的Postgres能连接到我的Postgres设置正确?

回答

0

只是简单的测试,如果你可以从node.js的连接向pgsql数据库,你可以用下面的代码片段:

const { Pool } = require('pg') 
const pool = new Pool() 

pool.query('SELECT NOW()', (err, res) => { 
    console.log(err, res) 
    pool.end() 
}) 

// or you can use async/await instead of callbacks 
const res = await pool.query('SELECT NOW()') 
console.log(res) 
await pool.end() 

这应返回包含当前日期时间pg.Result对象的形式响应。

节点Postgres使用相同的环境变量的libpq连接到PostgreSQL服务器,所以运行上面的代码,你可以调用它像这样:

PGUSER=postgres PGHOST=127.0.0.1 PGPASSWORD=mysecretpassword PGDATABASE=postgres PGPORT=5432 node script.js 

但是你必须提供连接的详细信息给你数据库实例。

所使用的环境变量的默认值是:

PGHOST='localhost' 
PGUSER=process.env.USER 
PGDATABASE=process.env.USER 
PGPASSWORD=null 
PGPORT=5432 

你也可以提供连接的详细信息编程,直接要么PoolClient实例。您也可以使用连接字符串URI。

您可以在“连接”部分的node-postgres documentation中阅读更多内容。

相关问题