current position:Home>Node. JS use get Stream download file
Node. JS use get Stream download file
2022-05-15 02:05:23【thankseveryday】
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
The sidebar is recommended
- How to add a widget as a high overlay
- Wigig antenna 10101r is applicable to T460 T4 wireless module m10101r
- Gigabit plug-in base series w13110vr wireless Gigabit receiver
- Es8388 low power audio chip and wireless transceiver chip cc1110f32rhhr IC RF
- Useeffect, react hooks / exclusive DEPs rule dependency resolution problem?
- React hook, how to dynamically add attributes to objects and render them to the page in time?
- Help react native run problems? Run Android error
- Vue learning summary
- Python experience lesson Chapter 1 01print function
- Python experience lesson Chapter 1 02 data types
guess what you like
Python experience lesson Chapter 1 03 conditional judgment
Vue - event handling
Node. JS: NVM tool usage NVM common commands
Solution to mask in element UI pop-up window
Online HTTP request header response header to JSON tool
Hospitality rental 90 react routing basic learning objectives
Summary of 89 react principle of hospitality rental
Ajax explanation (II)
Ajax implements user login authentication
Educoder web programming foundation autumn 2021 - HTML5 document header
Random recommended
- Educoder web programming foundation autumn 2021 - HTML5 - text control class label
- Educoder web programming foundation autumn 2021 - HTML5 document header tags and attributes
- Educoder web programming foundation autumn 2021 - HTML5 - text control class label
- Educoder web programming foundation autumn 2021 - overview of web front end development
- Vue data broker
- HTML5 notes - new specifications and new elements
- Lunch break train & problem thinking: on multidimensional array statistics of the number of elements
- Children's Painting Tutorial | children's interesting art lesson "firecrackers say goodbye to the old year and fireworks greet the new year"
- LeetCode 713. Subarray with product less than k
- JavaScript programming training Day6
- Vue realizes two-level linkage
- Tengine uses brotli to turn on tls1 3 and optimize HTTPS access speed
- C + +: remove the specified element from the array
- C + +: main elements
- Learn about nginx and tomact
- IC workplace Theory -- feelings of senior brother of digital ic front-end design after 4 months of employment (Part I)
- Vue Chapter 3 scaffolding's most complete render function, props, mixin mixing, plug-ins, browser local storage, component customization events_ Binding, unbinding, global event bus, message subscription and publishing, nexttick, Vue transition and animat
- Vue Chapter 5 vuex creates and introduces the use of store, getters and four map methods
- ***************2、 JS + Vue js***************
- A detailed explanation of HTTP protocol + classic interview questions
- Vue Chapter 4 Ajax in Vue: cross domain problems and slot slots
- Online nginx does not support the bug record of error reporting in delete request
- Okhttp sets the public parameters and puts the JSON object into the @ body to request the configuration of the public parameters
- Fluent ignores authentication of HTTPS and WSS certificates
- Browser loading HTML page evokes the most complete strategy of APP in mobile phone
- HTTP status code 304 and Etag details
- Using angularjs for fuzzy dynamic search drop-down box content
- Seamless connection to Macao, Hengqin Island, which is beautiful beyond the sky, is on fire again
- JQuery framework
- Vue mouse down and move event
- A simple Vue answer demo, single choice and multiple choice
- Front end interview question: if the cell in the table is red, click it to turn into white; if it is white, click it to turn into red, and what is not clicked is white
- Vue packaging folding panel plus animation effect
- If the front-end does real-time data acquisition?
- Ant vue3 table sorted by time
- Vue local refresh iframe
- Vue instruction authority
- Vue iframe refresh remains on the original page
- Vue realizes Gaode map API mask, positioning and weather
- Comparison and implementation of bidirectional data binding between react and Vue