Search code examples
javascriptnode.jsexpressnode-csv-parse

Cannot set headers after they are sent to the client while parsing data in node js


I am using csv parser to read csv file and passing received data of csv file to ejs template file to print so the data is in object format, so I have used stringyfy but getting error due to this.

Error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client:

Node js code

app.get('/', function (req, res, next) {
    fs.createReadStream('./Employee.csv')
        .pipe(csv())
        .on('data', function (rows) {
            try {
            var ParsedData=  data:JSON.stringify(rows);
                 res.render('Emp_details',{data:ParsedData});
            }
            catch (err) {
                //error handler
            }
        })
        .on('end', function () {
            //some final operation
        });


});

Code to print data in ejs template file:

<% for(var i = 1; i<= data1.length; i++) { %>
         <%=i %>
       <% } %>
    

Solution

  • You are getting the error because res.render can only be called once but you are calling it every time the data event fires.

    You need to call it where you put the comment //some final operation after collecting all the data.