0

I'm trying to write my database-data to a JSON. It works when I do not use the loop.

Then I get: TypeError: first argument must be a string or Buffer

I'm using the mysql npm package.

con.query('SELECT * FROM mydb.orders_view;', function(err, rows, fields) {
            if (err) {
                res.status(500).json({ result: 'Error' })
            }
            for (var i = 0; i < rows.length; i++) {

                 res.write(
                 {
                time: date,
                Order: [{
                    OrderedBy: rows[i]['OrderedBy']
                }]
               } 
            );
                }

            res.end();


        });
});
0

1 Answer 1

4

You're calling write with an object. According to the documentation, it must be a string or buffer:

chunk can be a string or a buffer. If chunk is a string, the second parameter specifies how to encode it into a byte stream. By default the encoding is 'utf8'. The last parameter callback will be called when this chunk of data is flushed.


Side note: You're not handling the error case properly, you probably want a return; in that initial if block so you don't continue to the loop when an error occurs.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I improved my error handling. Fixed the issue by using res.write(JSON.stringify).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.