Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
What is the difference between sending data using streams in node using 'data' event and 'open' event?

I have been trying to figure out the difference in the following two code snippets in node. On making the request from the browser both the code files shows transfer-encoding to be chunked. So, are these two methods same and if not what is the drawback of one over the other.

Method-1 :

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream("./bigFile.txt");
  stream.on("open", () => {
    stream.pipe(res);
  });
});

server.listen(3000, () => {
  console.log("server started");
});

Method-2 :

const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  const stream = fs.createReadStream("./bigFile.txt");
  stream.on("data", () => {
    stream.pipe(res);
  });
});

server.listen(3000, () => {
  console.log("server started");
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So, you don't have to wait for either event before piping the stream. The stream and the pipe operation will handle all that for you. So, you can just do this:

const stream = fs.createReadStream("./bigFile.txt");
stream.pipe(res);

The pipe operation will register itself for the data event and as data arrives on the readstream, it will write it out to the res stream. So, you don't need to do either of your options.

I would guess that this option:

stream.on("data", () => {
  stream.pipe(res);
 });

can actually cause a problem because the data event can occur more than once and then you'll be trying to call .pipe() more than once. You would not have that issue with the open event, though as I said above, you don't need to hook into either event yourself as .pipe() will do that for you

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda