1

I want to create a simple Node.js server and send data with pipe() method. But I have an issue.

The page loads when server started the first time, but when I refresh the page, it becomes blank. I mean the data is not loaded. Why does it happen?

var http = require('http'),
    fs = require('fs');

var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');


http.createServer(function (req, res) {  
    res.writeHead(200, {'Content-Type': 'text/plain'});
    myReadStream.pipe(res);
}).listen(3300);
Gino Pane
  • 4,740
  • 5
  • 31
  • 46

1 Answers1

2

This would work if you change it to:

http.createServer(function (req, res) {  
    var myReadStream = fs.createReadStream(__dirname + '/input.txt', 'utf8');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    myReadStream.pipe(res);
}).listen(3300);

That's because the stream once read is not rewinded automatically (in fact it cannot be).

But it's not the most flexible way to serve static content.

See this answer for five examples of serving static files with and without Express, from using high-level frameworks to very low level manual reinventing the wheel kind of implementation.

rsp
  • 107,747
  • 29
  • 201
  • 177
  • Ups! I thought server can reach the myReadStream variable everytime because it's global. Actually i am not trying to serve static content. I was just trying to use pipe and understand the way it works. – Mert Şafak Jul 19 '17 at 13:16
  • 1
    @MertŞafak Yes it can reach the variable, it's global, but once the stream is read then all the subsequent requests see the same finished stream. – rsp Jul 19 '17 at 13:17
  • @MertŞafak the reference to the stream will still be available but the stream itself [will have ended](https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options) as that's what it does at the end of `pipe()` – George Jul 19 '17 at 13:18
  • @George so moving stream into the server scope works because everytime i refreshed the page stream is buffered again? – Mert Şafak Jul 19 '17 at 13:20
  • @MertŞafak spot on :) but as rsp has stated, there are far better ways to serve up these kinds of files – George Jul 19 '17 at 13:22
  • OK. Thank you guys for your time :) – Mert Şafak Jul 19 '17 at 13:29