User Tools

Site Tools


njsetn:readable_file_streams

“Give us ways to handle continuous data flows”.

Both stdout & stdin implement the stream interface.

→ nodejs.org/api/stream.html

Récupération de la taille sans stream :

var fs = require("fs");

fs.readFile("file.log", "UTF-8", function(error, log) {
  console.log(`File Read ${log.length}`);
});
console.log("Reading File");
  1. on attend la lecture complète du fichier avant de lire la taille
  2. on buffer tout le fichier dans une seule variable

Version avec stream :

var s = require("fs");

var stream = fs.createReadStream("file.log", "UTF-8");

var data = "";

stream.once("data", function(chunk) {
  console.log("Started Reading File");
});

stream.on("data", function(chunk) {
  process.stdout.write(`chunk: ${chunk.length} | `);
  data += chunk;
});

stream.on("end", function(chunk) {
  console.log(`Finished Reading File ${data.length}`);
});
njsetn/readable_file_streams.txt · Last modified: 2016/03/24 09:12 by leo