EN
                                
                            
                        Node.js - PostgreSQL Create table if not exists
                                    0
                                    points
                                
                                In this article, we would like to show you how to create a table only if it doesn't exist in Node.js.
const { Client } = require('pg');
const client = new Client({
    host: '127.0.0.1',
    user: 'postgres',
    database: 'database_name',
    password: 'password',
    port: 5432,
});
const execute = async (query) => {
    try {
        await client.connect();     // gets connection
        await client.query(query);  // sends queries
        return true;
    } catch (error) {
        console.error(error.stack);
        return false;
    } finally {
        await client.end();         // closes connection
    }
};
const text = `
    CREATE TABLE IF NOT EXISTS "users" (
	    "id" SERIAL,
	    "name" VARCHAR(100) NOT NULL,
	    "role" VARCHAR(15) NOT NULL,
	    PRIMARY KEY ("id")
    );`;
execute(text).then(result => {
    if (result) {
        console.log('Table created');
    }
});
Database:
 
Native SQL query (used in the above example):
CREATE TABLE IF NOT EXISTS"users" (
	"id" SERIAL,
	"name" VARCHAR(100) NOT NULL,
	"role" VARCHAR(15) NOT NULL,
	PRIMARY KEY ("id")
);
Note:
To create a multi-line string, create a
template literalusingbackticks``.
