Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express - res.send() works once

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.

like image 214
Mahdi Dibaiee Avatar asked Mar 06 '13 14:03

Mahdi Dibaiee


People also ask

Does Res send end the function?

send doesn't return the function, but does close the connection / end the request.

What does Res send () do?

The res. send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client.

Do we need a return after Res send Express?

It is a common convention to not use exceptions/errors for ordinary control flow. I therefore recommend to place a return statement after the res. send call to make your function stop executing further. Save this answer.

Does Res json () Send?

json() Function. The res. json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.


2 Answers

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 :)

like image 100
robertklep Avatar answered Nov 06 '22 07:11

robertklep


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.

like image 35
user568109 Avatar answered Nov 06 '22 05:11

user568109