简体   繁体   English

如何使用Node.js net.Socket与Postgresql数据库通信就像使用终端一样

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

In the postgresql terminal I can type a command and get a response. 在postgresql终端中,我可以输入命令并获得响应。 For example: 例如:

# create database new database; #create database new database;

CREATE DATABASE 创建数据库

Above I enter in the terminal the command “create database newdatabase;” The database program responds “CREATE DATABASE” 上面我在终端输入命令“create database newdatabase;”数据库程序响应“CREATE DATABASE”

I am trying to do the same the thing but using a node net.Socket. 我试图做同样的事情,但使用节点net.Socket。 In other words, I want to issue commands to the postgresql server I have running on localhost:5432 and get a response back via a socket. 换句话说,我想向我在localhost:5432上运行的postgresql服务器发出命令,并通过套接字获得响应。

My program successfully sets up a connection with the postgresql server and successfully flushes the data to the kernel, but I never get a response (the data listener never gets fired). 我的程序成功建立了与postgresql服务器的连接,并成功将数据刷新到内核,但我从未得到响应(数据监听器永远不会被触发)。 The newdatabase does not get created either. 新数据库也不会被创建。

I also took a quick look at what happens on wireshark. 我还快速了解了wireshark上发生的事情。 It looks like the socket gets setup. 看起来套接字得到了设置。 I see my data get sent in cleartext. 我看到我的数据以明文形式发送。 The postgresql server then sends an ACK FIN ACK. postgresql服务器然后发送ACK FIN ACK。 I ACK FIN ACK and then the postgresql server ACKs one last time. 我确认FIN ACK,然后postgresql服务器最后一次确认。 So I know that the postgresql server does not send any data back. 所以我知道postgresql服务器不会发回任何数据。

My question is, why does the postgresql server ignore the command I send it and why does the postgresql server not send me any data back, even if that data is just an error. 我的问题是,为什么postgresql服务器会忽略我发送它的命令以及为什么postgresql服务器不会向我发回任何数据,即使该数据只是一个错误。

const net = require('net');
const BlueBird = require('bluebird');

BlueBird.coroutine(function* () {

var host = "127.0.0.1";
var port = "5432";
var idle_timeout = 10000;

var MySocket = new net.Socket();
MySocket.setTimeout(idle_timeout);

var data = yield new Promise(

    function resolver(resolve, reject) {

        MySocket.on('connect', function () {
            var flushed = MySocket.write("create database newdatabase;", "utf8");
            console.log("Data flushed to kernel: " + flushed);
        });

        MySocket.on('data', function (data) {
            console.log(data);
            resolve(data);
        });

        MySocket.on('error', function (error) {
            reject(error);
        });

        MySocket.connect(port, host);

    }

    );

    return data;

})()
.then(function (data) {

    console.log(data);

    return data;

})
.catch(function (error) {

    console.error(error);

})

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. psql是一个(REPL)命令行工具,它接受在一行或多行上输入的命令,并对其进行解析,并将其发送到数据库。

PostgreSQL is not talking the same textbased protocol over the socket on port 5432. You can read more about PostgreSQL protocol in their documentation . PostgreSQL没有通过端口5432上的套接字说出相同的基于文本的协议。您可以在他们的文档中阅读有关PostgreSQL协议的更多信息。

Use the pg module to connect to Postgres with node, and do the queries there: 使用pg模块连接到带节点的Postgres,并在那里进行查询:

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 : 通过pg-promise以更简单的方法扩展bolav的答案:

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
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM