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
Fetching URLs via JS resulting in empty files

All I want to do is have a nice and simple function that'll take an url and save it to a file, however every single implementation me or some JS developer friends have been able to come up with throughout the day gives the same end result: an empty file.

import * as fs from 'fs';
import * as path from 'path';
import fetch from 'node-fetch';
import { Headers } from 'node-fetch';

export function downloadURL(url, saveLocation) {
    const absSaveLocation = path.resolve(saveLocation);

    const myHeaders = new Headers();
    myHeaders.append('User-Agent', 'hifumi-js:v1.0.0');

    if (url.includes("pximg")) {
      myHeaders.append('Referer', 'https://www.pixiv.net/');
    }

    const requestOptions = {
      method: 'GET',
      headers: myHeaders,
    }

    const fileStream = fs.createWriteStream(absSaveLocation);
    fetch(url, requestOptions)
      .then(res => res.body.pipe(fileStream))
      .catch(error => console.log('error', error));
    fileStream.on('finish', () => {fileStream.close();});
}

I've tried a bunch of different libraries, including https, request, fetch, axios and all of them give me the same useless, empty file. It can't be the url as well since it's matched against a regex first before downloading and I've confirmed with countless different urls.

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

0

So I managed to fix this myself in the end by abandonding the whole idea of trying to use a stream to write to the file.

const fileStream = fs.createWriteStream(absSaveLocation);
    fetch(url, requestOptions)
      .then(res => res.body.pipe(fileStream))
      .catch(error => console.log('error', error));
    fileStream.on('finish', () => {fileStream.close();});

has now become

await fetch(url, requestOptions)
      .then(response => response.arrayBuffer())
      .then(buffer => fs.writeFile(absSaveLocation, new Uint8Array(buffer)))
      .catch(error => console.log('error', error));
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