Why is there a pause between a back-to-back println and print statement?

I am writing a simple HTTP request using the standard libraries net module:

use std::io::prelude::*;
use std::net;

fn main() -> std::io::Result<()> {
    let request = 
b"GET / HTTP/1.1
Host: localhost:8080

";

    let mut response = String::new();

    print!("Connecting...");
    let mut stream = net::TcpStream::connect("127.0.0.1:8080")
        .expect("Cannot connect to server");
    println!("Connected!");

    print!("Writing...");
    stream.write(request)
        .expect("Error writing");
    println!("Written!");

    print!("Reading...");
    stream.read_to_string(&mut response)
        .expect("Error reading");
    println!("Read!");

    println!("\nResponse:\n{}", response);
    Ok(())
}

I have a simple Express webserver running locally on localhost:8080.

const express = require('express')
const app = express()
const port = 8080

app.get('/', (req, res) => {
  console.time('/')
  res.send('ok')
  console.timeEnd('/')
})

app.listen(port, () => console.log(`Server on ${port}`))

When I run the program, there is a second or two pause between the printing of Written! and Reading.... Why does that pause occur when there seems to be nothing there to pause execution?

Server Output:

/: 5.168ms

Rust Output:

Connecting...Connected!
Writing...Written! // PAUSES HERE AT EOL!
Reading...Read!

Response:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 2
ETag: W/"2-eoX0dku9ba8cNUXvu/DyeabcC+s"
Date: Thu, 06 Dec 2018 22:32:47 GMT
Connection: keep-alive

ok
728x90

1 Answers Why is there a pause between a back-to-back println and print statement?

stdout is typically line buffered, meaning it stores whatever you write to it in a buffer until it sees a newline. So you won't see anything until println!("Read!"); prints a newline.

If you want to display the contents before that you need to flush the buffer.

use std::io;  // for io::stdout

...

print!("Reading...");
io::stdout().flush()?;

3 months ago