node.js - 使用 node-postgres 在 postgres 中存储文件

标签 node.js postgresql node-postgres

我正在尝试使用 node-postgres 模块将一个小文件存储到 postgres 数据库中。我知道我应该使用 bytea 数据类型来执行此操作。我遇到的问题是当我做类似的事情时:

fs.readFile path, (err, data) ->
    client.query 'UPDATE file_table SET file = $1 WHERE key = $2', [data, key], (e, result) ->
    ....

数据库中文件列的内容是:\x 并且没有存储任何内容。如果我将数据缓冲区更改为十六进制,即 data.toString('hex') 文件被存储,但当我读回文件时所有格式都丢失了。

使用 node-postgres 模块将文件存储到 postgres 的正确方法是什么?

最佳答案

诀窍是编码为十六进制并在文件前加上\x。通过返回缓冲区的 parseByteA 确实支持将其读回:

https://github.com/brianc/node-postgres/blob/master/lib/textParsers.js

这是我在 postgres 9.2.2 和 node.js 0.8.16 以及 node-postgres (npm package='pg') 0.11.2 上从磁盘读取图像的操作:

      fs.readFile(loc_on_disk, 'hex', function(err, imgData) {
        console.log('imgData',imgData);
        imgData = '\\x' + imgData;
        app.pgClient.query('insert into image_table (image) values ($1)',
                           [imgData],
                           function(err, writeResult) {
          console.log('err',err,'pg writeResult',writeResult);
        });
      });

我做了什么把它写回来

app.get('/url/to/get/', function(req, res, next) {
  app.pgClient.query('select image from image_table limit 1',
                     function(err, readResult) {
    console.log('err',err,'pg readResult',readResult);
    fs.writeFile('/tmp/foo.jpg', readResult.rows[0].image);
    res.json(200, {success: true});
  });
});

关于node.js - 使用 node-postgres 在 postgres 中存储文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124711/

相关文章:

node.js - 如何在node-postgres中捕获client.connect()?

node.js - 无法接收express.js中间件函数中的错误

sql - 查询匹配多行?

PostgreSQL - 删除重复记录 - 错误 : too many range table entries

sql - 如何将 .sql 文件的内容读入 R 脚本以运行查询?

node.js - 如何优化 Postgresql max_connections 和 node-postgres 连接池?

javascript - Node : How to replace certain characters within an array with other characters in javascript

node.js - 使用连接与 path.resolve 指定绝对路径有什么区别吗?

node.js - winston -MaxListenersExceededWarning : Possible EventEmitter memory leak detected

node.js - Postgres 服务器没有响应 nodejs 请求