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

171
Visualizações
I can't download a file with nodejs backend and react frontend

I am trying to download a requested file from the frontend to a backend server with nodejs. To do it in react I use axios and in nodejs I am using express. The problem is that with my implementation I get the following error:

Error [ERR_STREAM_CANNOT_PIPE]: Cannot pipe, not readable
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.pipe (node:_http_outgoing:987:22)
    at file:///home/marc/Disco/Projects/GymApp/server/routes/trainer.js:249:9
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on ServerResponse instance at:
    at ServerResponse.pipe (node:_http_outgoing:987:8)
    at file:///home/marc/Disco/Projects/GymApp/server/routes/trainer.js:249:9
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_STREAM_CANNOT_PIPE'

Here is the axios request:

const downloadTraining = async (id) => {
    const JWT = new ClassJWT();
    const axiosReq = axios.create();
    await JWT.checkJWT();
    axiosReq
      .post(`${serverPath}/download-training`, {
        trainer_id: await JWT.getId(),
        training_id: id,
        token: JWT.getToken(),
      })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => console.log(err));
  }

Here I don't know what to do for the browser to download the file, if anyone know it, let me know.

Here is the nodejs code with express that gives me the error that I mentioned above:

import express from "express";
import { verifyJWT } from "../services/tokens/verifyJWT.js";
import Training from "../models/Training.js";
import fs from "fs";

const path = "/home/marc/Disco/Projects/AtlasFitness/";
const dirname = "uploads/trainings/";

routerTrainer.post("/download-training", verifyJWT, async (req, res) => {
  const { trainer_id, training_id } = req.body;
  let training = await Training.findOne({
    where: { id: training_id, trainer_id },
  });

  if (training) {
    const filePath = fs.createWriteStream(`${path}${dirname}${training.file_id}`);
    res.pipe(filePath);
    filePath.on('finish',() => {
        filePath.close();
        console.log('Download Completed'); 
    })
  }
})

Here is when I get the error, if anyone know how to fix it to get the file downloaded to the user's computer, please let me know it.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It should be a read stream on the API, not a write stream.

const filePath = fs.createReadStream(`${path}${dirname}${training.file_id}`);
        res.pipe(filePath);
        filePath.on('finish',() => {
            filePath.close();
            console.log('Download Completed'); 
        })
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