使用node-postgres将文件存储在postgres中

我正在尝试使用node-postgres模块将一个小文件存储到postgres数据库中。 我明白,我应该使用bytea数据types来做到这一点。 我遇到的问题是当我做一些事情时:

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

数据库中文件列的内容是:\ x并且不存储任何内容。 如果我更改数据缓冲区为hex即data.toString('hex')文件存储,但所有格式都会丢失,当我读取文件退出。

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

窍门是编码为hex,并用\ 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}); }); });