-
-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy path03-curly-abort-streams.js
More file actions
52 lines (45 loc) · 1.39 KB
/
03-curly-abort-streams.js
File metadata and controls
52 lines (45 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Copyright (c) Jonathan Cardoso Machado. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Example showing how one could download only the start of a big file
// using streams with the`curly` async fn
const fs = require('fs')
const { curly, CurlCode } = require('../dist')
const run = async () => {
const { data: stream } = await curly.get(
'https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4',
{
// we want the unparsed binary response to be returned as a stream to us
curlyStreamResponse: true,
curlyResponseBodyParsers: false,
},
)
// we are going to write the response stream to this file
const writableStream = fs.createWriteStream('big_buck_bunny_720p_1mb.mp4')
let count = 0
stream.on('data', (chunk) => {
count += chunk.length
console.info('downloaded', Math.floor(count / 1000), 'KB')
// abort after 50KB
if (count >= 65536) {
console.info('abort download')
stream.destroy()
}
})
stream.on('error', (err) => {
if (err.isCurlError && err.code === CurlCode.CURLE_ABORTED_BY_CALLBACK) {
// this is expected
} else {
throw err
}
})
stream.pipe(writableStream)
}
run()
.then(() => console.log('finished!'))
.catch((error) => {
console.error('error: ', error)
})