Get a stream as a string, Buffer, ArrayBuffer or array
Installations
npm install get-stream
Developer
sindresorhus
Developer Guide
Module System
ESM
Min. Node Version
>=18
Typescript Support
No
Node Version
20.11.1
NPM Version
9.2.0
Statistics
342 Stars
124 Commits
32 Forks
11 Watching
1 Branches
17 Contributors
Updated on 21 Nov 2024
Languages
JavaScript (91.31%)
TypeScript (8.69%)
Total Downloads
Cumulative downloads
Total Downloads
17,952,788,790
Last day
-8.1%
19,470,222
Compared to previous day
Last week
1.6%
115,238,915
Compared to previous week
Last month
12.1%
470,844,253
Compared to previous month
Last year
17.3%
4,755,398,779
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Dev Dependencies
7
get-stream
Get a stream as a string, Buffer, ArrayBuffer or array
Features
- Works in any JavaScript environment (Node.js, browsers, etc.).
- Supports text streams, binary streams and object streams.
- Supports async iterables.
- Can set a maximum stream size.
- Returns partially read data when the stream errors.
- Fast.
Install
1npm install get-stream
Usage
Node.js streams
1import fs from 'node:fs'; 2import getStream from 'get-stream'; 3 4const stream = fs.createReadStream('unicorn.txt'); 5 6console.log(await getStream(stream)); 7/* 8 ,,))))))));, 9 __)))))))))))))), 10\|/ -\(((((''''((((((((. 11-*-==//////(('' . `)))))), 12/|\ ))| o ;-. '((((( ,(, 13 ( `| / ) ;))))' ,_))^;(~ 14 | | | ,))((((_ _____------~~~-. %,;(;(>';'~ 15 o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~ 16 ; ''''```` `: `:::|\,__,%% );`'; ~ 17 | _ ) / `:|`----' `-' 18 ______/\/~ | / / 19 /~;;.____/;;' / ___--,-( `;;;/ 20 / // _;______;'------~~~~~ /;;/\ / 21 // | | / ; \;;,\ 22 (<_ | ; /',/-----' _> 23 \_| ||_ //~;~~~~~~~~~ 24 `\_| (,~~ 25 \~\ 26 ~~ 27*/
Web streams
1import getStream from 'get-stream'; 2 3const {body: readableStream} = await fetch('https://example.com'); 4console.log(await getStream(readableStream));
This works in any browser, even the ones not supporting ReadableStream.values()
yet.
Async iterables
1import {opendir} from 'node:fs/promises'; 2import {getStreamAsArray} from 'get-stream'; 3 4const asyncIterable = await opendir(directory); 5console.log(await getStreamAsArray(asyncIterable));
API
The following methods read the stream's contents and return it as a promise.
getStream(stream, options?)
stream
: stream.Readable
, ReadableStream
, or AsyncIterable<string | Buffer | ArrayBuffer | DataView | TypedArray>
options
: Options
Get the given stream
as a string.
getStreamAsBuffer(stream, options?)
Get the given stream
as a Node.js Buffer
.
1import {getStreamAsBuffer} from 'get-stream'; 2 3const stream = fs.createReadStream('unicorn.png'); 4console.log(await getStreamAsBuffer(stream));
getStreamAsArrayBuffer(stream, options?)
Get the given stream
as an ArrayBuffer
.
1import {getStreamAsArrayBuffer} from 'get-stream'; 2 3const {body: readableStream} = await fetch('https://example.com'); 4console.log(await getStreamAsArrayBuffer(readableStream));
getStreamAsArray(stream, options?)
Get the given stream
as an array. Unlike other methods, this supports streams of objects.
1import {getStreamAsArray} from 'get-stream'; 2 3const {body: readableStream} = await fetch('https://example.com'); 4console.log(await getStreamAsArray(readableStream));
options
Type: object
maxBuffer
Type: number
Default: Infinity
Maximum length of the stream. If exceeded, the promise will be rejected with a MaxBufferError
.
Depending on the method, the length is measured with string.length
, buffer.length
, arrayBuffer.byteLength
or array.length
.
Errors
If the stream errors, the returned promise will be rejected with the error
. Any contents already read from the stream will be set to error.bufferedData
, which is a string
, a Buffer
, an ArrayBuffer
or an array depending on the method used.
1import getStream from 'get-stream'; 2 3try { 4 await getStream(streamThatErrorsAtTheEnd('unicorn')); 5} catch (error) { 6 console.log(error.bufferedData); 7 //=> 'unicorn' 8}
Browser support
For this module to work in browsers, a bundler must be used that either:
- Supports the
exports.browser
field inpackage.json
- Strips or ignores
node:*
imports
Most bundlers (such as Webpack) support either of these.
Additionally, browsers support web streams and async iterables, but not Node.js streams.
Tips
Alternatives
If you do not need the maxBuffer
option, error.bufferedData
, nor browser support, you can use the following methods instead of this package.
streamConsumers.text()
1import fs from 'node:fs'; 2import {text} from 'node:stream/consumers'; 3 4const stream = fs.createReadStream('unicorn.txt', {encoding: 'utf8'}); 5console.log(await text(stream))
streamConsumers.buffer()
1import {buffer} from 'node:stream/consumers'; 2 3console.log(await buffer(stream))
streamConsumers.arrayBuffer()
1import {arrayBuffer} from 'node:stream/consumers'; 2 3console.log(await arrayBuffer(stream))
readable.toArray()
1console.log(await stream.toArray())
Array.fromAsync()
If your environment supports it:
1console.log(await Array.fromAsync(stream))
Non-UTF-8 encoding
When all of the following conditions apply:
getStream()
is used (as opposed togetStreamAsBuffer()
orgetStreamAsArrayBuffer()
)- The stream is binary (not text)
- The stream's encoding is not UTF-8 (for example, it is UTF-16, hexadecimal, or Base64)
Then the stream must be decoded using a transform stream like TextDecoderStream
or b64
.
1import getStream from 'get-stream'; 2 3const textDecoderStream = new TextDecoderStream('utf-16le'); 4const {body: readableStream} = await fetch('https://example.com'); 5console.log(await getStream(readableStream.pipeThrough(textDecoderStream)));
Blobs
getStreamAsArrayBuffer()
can be used to create Blobs.
1import {getStreamAsArrayBuffer} from 'get-stream'; 2 3const stream = fs.createReadStream('unicorn.txt'); 4console.log(new Blob([await getStreamAsArrayBuffer(stream)]));
JSON streaming
getStreamAsArray()
can be combined with JSON streaming utilities to parse JSON incrementally.
1import fs from 'node:fs'; 2import {compose as composeStreams} from 'node:stream'; 3import {getStreamAsArray} from 'get-stream'; 4import streamJson from 'stream-json'; 5import streamJsonArray from 'stream-json/streamers/StreamArray.js'; 6 7const stream = fs.createReadStream('big-array-of-objects.json'); 8console.log(await getStreamAsArray( 9 composeStreams(stream, streamJson.parser(), streamJsonArray.streamArray()), 10));
Benchmarks
Node.js stream (100 MB, binary)
getStream()
: 142mstext()
: 139msgetStreamAsBuffer()
: 106msbuffer()
: 83msgetStreamAsArrayBuffer()
: 105msarrayBuffer()
: 81msgetStreamAsArray()
: 24msstream.toArray()
: 21ms
Node.js stream (100 MB, text)
getStream()
: 90mstext()
: 89msgetStreamAsBuffer()
: 127msbuffer()
: 192msgetStreamAsArrayBuffer()
: 129msarrayBuffer()
: 195msgetStreamAsArray()
: 89msstream.toArray()
: 90ms
Web ReadableStream (100 MB, binary)
getStream()
: 223mstext()
: 221msgetStreamAsBuffer()
: 182msbuffer()
: 153msgetStreamAsArrayBuffer()
: 171msarrayBuffer()
: 155msgetStreamAsArray()
: 83ms
Web ReadableStream (100 MB, text)
getStream()
: 141mstext()
: 139msgetStreamAsBuffer()
: 91msbuffer()
: 80msgetStreamAsArrayBuffer()
: 89msarrayBuffer()
: 81msgetStreamAsArray()
: 21ms
FAQ
How is this different from concat-stream
?
This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, Buffer
, an ArrayBuffer
or an array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge readable-stream
package.
Related
- get-stdin - Get stdin as a string or buffer
- into-stream - The opposite of this package
No vulnerabilities found.
Reason
security policy file detected
Details
- Info: security policy file detected: .github/security.md:1
- Info: Found linked content: .github/security.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/security.md:1
- Info: Found text in security policy: .github/security.md:1
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: license:0
- Info: FSF or OSI recognized license: MIT License: license:0
Reason
Found 24/30 approved changesets -- score normalized to 8
Reason
1 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/get-stream/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/get-stream/main.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:21
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 24 are checked with a SAST tool
Score
4.9
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More