current position:Home>Node. JS use get Stream download file

Node. JS use get Stream download file

2022-05-15 02:05:23thankseveryday

got yes node.js complete HPPT request Module .

Right API Completing a request is very simple :

const got = require("got");

got(url)
  .then(response => console.log(response.body))
  .catch(error => console.log(error.response.body));

Download files can use got.stream Method , Or set got Request parameters isStream: true

got.stream(url);
// or
got(url, {
     isStream: true });

got Of stream yes “ Duplex stream ”, Can read but write . To download the file, we just need to read . Download a file , We need to send the response to the file system in some way . Streams allow you to pipe data from one stream to another . Use fs Modular createWriteStream Method writes the stream to a file .

const got = require("got");
const {
     createWriteStream } = require("fs");

const url =
  "https://media0.giphy.com/media/4SS0kfzRqfBf2/giphy.gif";

got.stream(url).pipe(createWriteStream('image.gif'));

To deal with progress and errors , Let's separate the fetch stream from the write stream :

const got = require("got");
const {
     createWriteStream } = require("fs");

const url = "https://media0.giphy.com/media/4SS0kfzRqfBf2/giphy.gif";
const fileName = "image.gif";

const downloadStream = got.stream(url);
const fileWriterStream = createWriteStream(fileName);

such , We can download the stream downloadStream Import to File write stream fileWriterStream Before , Add listening Events .
Listening events have three properties :

  • transferred: Number of bytes transferred
  • total: Total bytes of file
  • percent: Percentage completed ( The value range is 0 To 1 Between )
const got = require("got");
const {
     createWriteStream } = require("fs");

const url = "https://media0.xxx.com/media/4SS0kfzRqfBf2/xxx.gif";
const fileName = "xxx.gif";

const downloadStream = got.stream(url);
const fileWriterStream = createWriteStream(fileName);

downloadStream
  .on("downloadProgress", ({
      transferred, total, percent }) => {
    
    const percentage = Math.round(percent * 100);
    console.error(`progress: ${
      transferred}/${
      total} (${
      percentage}%)`);
  })
  .on("error", (error) => {
    
    console.error(`Download failed: ${
      error.message}`);
  });

fileWriterStream
  .on("error", (error) => {
    
    console.error(`Could not write file to system: ${
      error.message}`);
  })
  .on("finish", () => {
    
    console.log(`File downloaded to ${
      fileName}`);
  });

downloadStream.pipe(fileWriterStream);

stream modular There is one pipeline Method , Rewrite the above code :

const got = require("got");
const {
     createWriteStream } = require("fs");
const stream = require("stream");
const {
     promisify } = require("util");
const pipeline = promisify(stream.pipeline);

const url = "https://media0.giphy.com/media/4SS0kfzRqfBf2/giphy.gif";
const fileName = "image.gif";

const downloadStream = got.stream(url);
const fileWriterStream = createWriteStream(fileName);

downloadStream.on("downloadProgress", ({
      transferred, total, percent }) => {
    
  const percentage = Math.round(percent * 100);
  console.error(`progress: ${
      transferred}/${
      total} (${
      percentage}%)`);
});

pipeline(downloadStream, fileWriterStream)
  .then(() => console.log(`File downloaded to ${
      fileName}`))
  .catch((error) => console.error(`Something went wrong. ${
      error.message}`));

You can also use async/await

......
(async () => {
    
  try {
    
    await pipeline(downloadStream, fileWriterStream);
    console.log(`File downloaded to ${
      fileName}`);
  } catch (error) {
    
    console.error(`Something went wrong. ${
      error.message}`);
  }
})();
......

copyright notice
author[thankseveryday],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/132/202205120527259808.html

Random recommended