• features
  • 连接

环境变量

¥Environment variables

node-postgres 使用与 libpq 和 psql 相同的 环境变量 连接到 PostgreSQL 服务器。单个客户端和池都将使用这些环境变量。这是一个将 node.js 连接到 PostgreSQL 服务器的小程序:

¥node-postgres uses the same environment variables as libpq and psql to connect to a PostgreSQL server. Both individual clients & pools will use these environment variables. Here's a tiny program connecting node.js to the PostgreSQL server:

import pg from 'pg'
const { Pool, Client } = pg
 
// pools will use environment variables
// for connection information
const pool = new Pool()
 
// you can also use async/await
const res = await pool.query('SELECT NOW()')
await pool.end()
 
// clients will also use environment variables
// for connection information
const client = new Client()
await client.connect()
 
const res = await client.query('SELECT NOW()')
await client.end()

要运行上述程序并指定要连接到哪个数据库,我们可以像这样调用它:

¥To run the above program and specify which database to connect to we can invoke it like so:

$ PGUSER=dbuser \
  PGPASSWORD=secretpassword \
  PGHOST=database.server.com \
  PGPORT=3211 \
  PGDATABASE=mydb \
  node script.js

这使我们能够编写程序而无需在程序中指定连接信息,并允许我们重用它们来连接到不同的数据库而无需修改代码。

¥This allows us to write our programs without having to specify connection information in the program and lets us reuse them to connect to different databases without having to modify the code.

使用的环境变量的默认值为:

¥The default values for the environment variables used are:

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

编程式

¥Programmatic

node-postgres 还支持使用连接信息以编程方式配置池或客户端。这是我们上面的相同脚本,经过修改后可使用编程(在本例中为硬编码)值。如果你的应用已经有办法管理配置值,或者你不想使用环境变量,那么这将非常有用。

¥node-postgres also supports configuring a pool or client programmatically with connection information. Here's our same script from above modified to use programmatic (hard-coded in this case) values. This can be useful if your application already has a way to manage config values or you don't want to use environment variables.

import pg from 'pg'
const { Pool, Client } = pg
 
const pool = new Pool({
  user: 'dbuser',
  password: 'secretpassword',
  host: 'database.server.com',
  port: 3211,
  database: 'mydb',
})
 
console.log(await pool.query('SELECT NOW()'))
 
const client = new Client({
  user: 'dbuser',
  password: 'secretpassword',
  host: 'database.server.com',
  port: 3211,
  database: 'mydb',
})
 
await client.connect()
 
console.log(await client.query('SELECT NOW()'))
 
await client.end()

许多云提供商都包含使用短期身份验证令牌连接到数据库实例的替代方法。node-postgres 通过回调函数支持动态密码,无论是同步还是异步。回调函数必须解析为字符串。

¥Many cloud providers include alternative methods for connecting to database instances using short-lived authentication tokens. node-postgres supports dynamic passwords via a callback function, either synchronous or asynchronous. The callback function must resolve to a string.

import pg from 'pg'
const { Pool } = pg
import { RDS } from 'aws-sdk'
 
const signerOptions = {
  credentials: {
    accessKeyId: 'YOUR-ACCESS-KEY',
    secretAccessKey: 'YOUR-SECRET-ACCESS-KEY',
  },
  region: 'us-east-1',
  hostname: 'example.aslfdewrlk.us-east-1.rds.amazonaws.com',
  port: 5432,
  username: 'api-user',
}
 
const signer = new RDS.Signer()
 
const getPassword = () => signer.getAuthToken(signerOptions)
 
const pool = new Pool({
  user: signerOptions.username,
  password: getPassword,
  host: signerOptions.hostname,
  port: signerOptions.port,
  database: 'my-db',
})

Unix 域套接字

¥Unix Domain Sockets

也可以建立与 unix 套接字的连接。这在 Ubuntu 等发行版上非常有用,因为这些发行版通过套接字连接而不是密码来管理身份验证。

¥Connections to unix sockets can also be made. This can be useful on distros like Ubuntu, where authentication is managed via the socket connection instead of a password.

import pg from 'pg'
const { Client } = pg
client = new Client({
  user: 'username',
  password: 'password',
  host: '/cloudsql/myproject:zone:mydb',
  database: 'database_name',
})

连接 URI

¥Connection URI

你也可以使用连接字符串 URI 初始化池和客户端。这在 Heroku 等环境中很常见,其中数据库连接字符串通过环境变量提供给你的应用 dyno。pg-connection-string 为你提供连接字符串解析。

¥You can initialize both a pool and a client with a connection string URI as well. This is common in environments like Heroku where the database connection string is supplied to your application dyno through an environment variable. Connection string parsing brought to you by pg-connection-string.

import pg from 'pg'
const { Pool, Client } = pg
const connectionString = 'postgresql://dbuser:secretpassword@database.server.com:3211/mydb'
 
const pool = new Pool({
  connectionString,
})
 
await pool.query('SELECT NOW()')
await pool.end()
 
const client = new Client({
  connectionString,
})
 
await client.connect()
 
await client.query('SELECT NOW()')
 
await client.end()
Last updated on August 24, 2024