1

我有以下测试代码:

const compression = require('compression');
const bodyParser = require('body-parser')
const cors = require('cors')
const { pool, connectionString } = require('./config')
const { handleError, ErrorHandler } = require('./error')

const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors())
app.use(compression());
const getEvents = (request, response) => {
    pool.connect((err, client, release) => {
        if (err) {
            throw new ErrorHandler(500, err.stack);
        }
        if(!request.query.FromTime){
            throw new ErrorHandler(400, 'Required paramter FromTime is missing.');
        }
        if(!request.query.ToTime){
            throw new ErrorHandler(400, 'Required paramter ToTime is missing.');
        }
        let fromtime = request.query.FromTime
        let totime = request.query.ToTime
        console.log("FromTime: ",fromtime," ToTime: ",totime);
        let query = 'SELECT data FROM logs WHERE time BETWEEN '+fromtime+' AND '+totime+' ORDER BY time DESC';
        console.log(query)
        var stream = client.query(query, (error, results) => {
            if (error) {
                throw new ErrorHandler(500,error);
            }
            response.status(200).json(results.rows)
        })
    })
}
...
app
  .route('/events')
  // GET endpoint
  .get(getEvents)
  // POST endpoint
  .post(addEvent)

app.use((err, req, res, next) => {
  handleError(err, res);
});
// Start server
app.listen(process.env.PORT || 3002, () => {
  console.log(`Server listening`)
})

我一直试图让它流式传输数据,但没有成功。我确实尝试了带有querystream的pg-query-stream,但最终出现以下错误,当我尝试时

var stream = client.query(new QueryStream(query));
stream.pipe(response);

_http_outgoing.js:607 抛出新的 ERR_INVALID_ARG_TYPE('第一个参数', ^

TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串或缓冲区类型之一。在 ServerResponse.write (/usr/src/app/node_modules/compression/index.js:89:18) 在 ServerResponse.write (_http_outgoing.js:579:10) 处的 write_ (_http_outgoing.js:607:11) 接收到类型对象) 在 PgQueryStream.ondata (_stream_readable.js:705:22) 在 PgQueryStream.emit (events.js:193:13) 在 addChunk (_stream_readable.js:295:12) 在 readableAddChunk (_stream_readable.js:276:11) 在PgQueryStream.Readable.push (_stream_readable.js:231:10) 在 cursor.read (/usr/src/app/node_modules/pg-query-stream/index.js:55:14) 在 Immediate.setImmediate (/usr/ src/app/node_modules/pg-cursor/index.js:91:7)

4

1 回答 1

4

响应流默认不支持对象模式。就像在文档中一样尝试

const JSONStream = require('JSONStream')
stream.pipe(JSONStream.stringify()).pipe(response)
于 2019-10-18T14:08:23.350 回答