How to Use Node.js net.Socket To Communicate with Postgresql Database Like One Would Using Terminal How to Use Node.js net.Socket To Communicate with Postgresql Database Like One Would Using Terminal database database

How to Use Node.js net.Socket To Communicate with Postgresql Database Like One Would Using Terminal


psql is a (REPL) command line tool which takes a command entered on one or several lines, and parses it, and sends it to the database.

PostgreSQL is not talking the same textbased protocol over the socket on port 5432. You can read more about PostgreSQL protocol in their documentation.

Use the pg module to connect to Postgres with node, and do the queries there:

var pg = require('pg');var conString = "postgres://username:password@localhost/database";pg.connect(conString, function(err, client, done) {  if(err) {    return console.error('error fetching client from pool', err);  }  client.query('create database newdatabase', function(err, result) {    console.log('CREATE DATABASE');  });}    


Extending on the answer by bolav, with a simpler approach via pg-promise:

var pgp = require('pg-promise')(/*options*/);var db = pgp("postgres://username:password@host:port/database");db.query("CREATE DATABASE NewDatabase")    .then(function (data) {        // success    })    .catch(function (error) {        // error    });