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:
-
Open the terminal of your project.
-
Type the following commands:
npm install pg
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.
Article ID: 2339, Created: Today at 2:34 AM, Modified: Today at 2:34 AM