Search code examples
javascriptexpressknex.js

knex.js pipe to express


i have a problem in knex.js and express, code like below:

userRouter.get('/:userId', function (req, res) {
  DB('users').where({
    id: req.params.userId
  }).first('name').pipe(res);
});

as knex.js doc wrote: there is a stream interface for knex.js query.

but i can not pipe the result to express(node http api) response.

the code above does not work.

there is a "TypeError":

TypeError: first argument must be a string or Buffer

what went wrong?


Solution

  • Create a stream and pipe it first to JSONStream and finally pipe it to your response object

    var knex = require('knex')({
      client: 'mysql',
      connection: {
        host     : '...',
        user     : '...',
        password : '...',
        database : '...'
      }
    });
    var JSONStream = require('JSONStream');
    var express = require('express');
    var app = express();
    
    app.get('/', function (req, res) {
        var sql = knex.select('*').from('table').limit(3);
        res.set('Content-Type', 'application/json');
        sql.stream().pipe(JSONStream.stringify()).pipe(res);
    });
    
    var server = app.listen(3000, function () {
      var host = server.address().address;
      var port = server.address().port;
    
      console.log('Example app listening at http://%s:%s', host, port);
    });