Express – res.send() works once

All we need is an easy explanation of the problem, so here it is.

I’m new to Node and Express, I was trying to make something with Express just to get started, then I faced this problem.

First res.send() works well, but the second one doesn’t fire.

Here’s my code:

var express = require('express'),
    app     = express(),
    fs      = require('fs'),
    visits;


app.listen(8080);

app.get('/', function(req,res) {

    res.send('Hello');

    fs.readFile('counter.txt','utf-8', function(e,d) {

        if (e) { 
            console.log(e);
        }
        else {
            console.log(parseInt(d) + 1);
            fs.writeFile('counter.txt',parseInt(d) + 1);
            res.send('<p id="c">' + ( parseInt(d) + 1 ) + '</p>');
        }

    })
...

‘Hello’ is sent, but res.send('<p> .. </p>'); isn’t. If I comment res.send('Hello');, visitors will be shown.

Thanks in advance.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

res.send() is meant to be called just once.

Try this instead:

app.get('/', function(req,res) {
  var response = 'Hello';
  fs.readFile('counter.txt','utf-8', function(e,d) {
      if (e) {
        console.log(e);
        res.send(500, 'Something went wrong');
      }
      else {
        console.log(parseInt(d) + 1);
        fs.writeFile('counter.txt',parseInt(d) + 1);
        response += '<p id="c">' + ( parseInt(d) + 1 ) + '</p>';
        res.send(response);
      }
  })
});

(or just res.send("Hello<p id=..."), but you get the point 🙂

Method 2

This is because res.send() finishes sending the response.

When res.send('Hello'); is encountered it sends the response immediately. So next res.send is not executed and you cannot see visitors. Commenting the first res.send allows you to view the second one.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply