Using knex.js to pipe data to an express server

I'm encountering an issue with knex.js and express. Here is the code snippet in question:

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

According to the knex.js documentation, there is a stream interface for knex.js query.

However, I am unable to pipe the result to the express(node http api) response.

The code mentioned above is not functioning correctly.

An error message "TypeError" is being displayed:

TypeError: first argument must be a string or Buffer

What could have caused this issue?

Answer №1

To begin, establish a stream and direct it through JSONStream before connecting 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);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Compatibility issues with jQuery observed in Firefox and Internet Explorer 11

Check out the code here: jsfiddle demo HTML CODE: <div class="first"> <!-- Part one --> <div class="acord_col"> <div class="img_class" id="exist_site"></div> <div class="intro_text"> </div> </div&g ...

Encountering numerous errors when attempting to incorporate lottie-web into my JavaScript file

I am in the process of creating a unique audio player for my website utilizing HTML, CSS, and JavaScript. I encountered some challenges while trying to get it to work effectively on Codepen as well as my text editor. The animations were not functioning pro ...

A distinct handler function designed for a dynamically generated form

I have 3 MaterialUI TextFields that are rendered n number of times based on user input (stored in a variable named groupMembersCount) in a functional ReactJS component using the useState hook: const [groupDetails, setGroupDetails] = React.useState([ { ...

What is the solution for the error "Firebase limitToLast is undefined"?

How can I restrict the number of items returned when watching the 'value' in my Firebase database? I keep getting an undefined error when using orderByChild on my Firebase reference. $scope.watchRef = new Firebase(ActiveFirebase.getBaseURL() ...

AngularJS single page applications experiencing issues with loading scripts and stylesheets upon page reload

Homepage Setup : <ng-view></ng-view> Angular Routing Configuration : when('/', { url: '/', templateUrl: 'site/home', controller: 'indexController' }). when(&apos ...

What is causing my ReactJS web application to not recognize the cookies being sent by the backend server?

I have a web application with a frontend built in ReactJS and a backend built in HapiJS. The backend is running on http://localhost:3000 and the frontend on http://localhost:1234. My goal is to implement authentication using cookies. I am using Axios in m ...

Guide on incorporating a Virtual field post querying a different Model

I need the commentCount field to display whenever I access the Image model. Below is the code snippet: imageSchema .virtual('commentCount') .get(async function () { const image_id = this._id; const commentCount = await Comment.count( ...

PHP Temp File Not Found After AJAX File Upload

Recently, I've been researching how to upload files through AJAX using FormData and FileReader. However, I keep encountering a recurring issue. After initiating the file upload process, the file is sent to a PHP script for validation and then an atte ...

This API is no longer compatible with India's payment system, so you won't be able to process payments using Next.js, Strapi, or

I am currently developing a website using "next js" as the frontend and "Strapi" as the backend for a simple ecommerce project. The payment gateway being utilized is "Stripe". I have implemented the checkout code in both the frontend and backend, and every ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...

Angular 1 and Javascript offer a different approach than using lodash omit and the delete operator

I am facing an issue with a child component where I need to remove properties from an object. Normally, using Lodash, it should work with the following code snippet: this.current.obj = omit(this.current.obj, ['sellerSupportWeb', 'sellerSup ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

Tips for attaching inline styles to the body element with a vuejs component

I am new to vue.js and have been learning for a couple of days now. There are still some concepts that I am struggling to understand. I am currently working on creating a dropdown menu that appears when the user clicks on three dots. However, I am facing a ...

"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestio ...

Displaying local time alongside global time using PHP

I have a challenge - I am storing time in DATETIME format and now I need to display it in the local timezone. Does anyone know how to achieve this using PHP? ...

What specific design scheme is employed in the MEANJS project?

After transitioning from PHP to NodeJs and working on a MEANJS project, I encountered an issue where I couldn't use a controller method in another controller. It seems like I may have followed the wrong pattern. student.model.js ----------------- var ...

Utilize Knex, Express, and NodeJS to enable users to log in and register

I am currently developing an application with Knex-MySQL, Express, and NodeJS. To showcase my code, I have uploaded it to a Plunker. As for the frontend, I haven't started working on that yet, so I am testing the functionality using Postman. The regi ...

JavaScript prototypal inheritance concept

During my free time, I like to dabble in JavaScript, but I’m currently struggling with this particular topic. var person = new Person("Bob", "Smith", 52); var teacher = new Teacher("Adam", "Greff", 209); function Humans(firstName, lastName) { this. ...