EN
Node.js - PostgreSQL Create database
0 points
In this article, we would like to show you how to create a PostgreSQL database in Node.js.
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
password: 'password',
7
port: 5432,
8
});
9
10
const createDatabase = async () => {
11
try {
12
await client.connect(); // gets connection
13
await client.query('CREATE DATABASE my_database'); // sends queries
14
return true;
15
} catch (error) {
16
console.error(error.stack);
17
return false;
18
} finally {
19
await client.end(); // closes connection
20
}
21
};
22
23
createDatabase().then((result) => {
24
if (result) {
25
console.log('Database created');
26
}
27
});
28