Connecting to PostgreSQL using Node.js

Programming, error messages and sample code > Node.js

The node-postgres package includes all of the functionality you need to access and work with PostgreSQL databases in Node.js. Before you can do this, however, you must install the node-postgres package on your account. To do this, follow these steps:

  1. Open the terminal of your project.

  2. Type the following commands:

    npm install pg

Code sample

After you install the node-postgres package, you are ready to work with PostgreSQL databases and manipulate data in them. The following sample Node.js code demonstrates how to do this.

In your own code, replace dbname with the database name, username with the PostgreSQL database username, and password with the database user's password. Additionally, you should modify the SELECT query to match a table in your own database:

import pg from 'pg';

const { Client } = pg;
const client = new Client({
    host: 'localhost',
    database: 'dbname',
    user: 'username',
    password: 'password',
});

await client.connect();
 
const res = await client.query('SELECT * FROM table_name');
console.log(res.rows[0]);
await client.end();

You may receive the following error message when you try to run this code:

SyntaxError: Cannot use import statement outside a module

If you receive this error message, create a package.json file in the same directory as the code file. Copy the following text and then paste it into the package.json file:

{
    "type": "module"
}
The code should now run.

More information

For more information about the node-postgres package, please visit https://node-postgres.com/.