Skip to content

Latest commit

 

History

History
29 lines (23 loc) · 698 Bytes

section21.1.md

File metadata and controls

29 lines (23 loc) · 698 Bytes

Section 21.1: Read Data from TextFile with Streams

I/O in node is asynchronous, so interacting with the disk and network involves passing callbacks to functions. You might be tempted to write code that serves up a file from disk like this:

let http = require('http');
let fs = require('fs');

let server = http.createServer(function (req, res) {
  fs.readFile(__dirname + '/data.txt', function (err, data) {
    res.end(data);
  });
});

server.listen(3000);
let http = require('http');
let fs = require('fs');

let server = http.createServer(function (req, res) {
  let stream = fs.createReadStream(__dirname + '/data.txt');
  stream.pipe(res);
});

server.listen(3000);