• Stars
    star
    420
  • Rank 99,752 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 11 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!

bl (BufferList)

Build Status

A Node.js Buffer list collector, reader and streamer thingy.

NPM

bl is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them!

The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently.

const { BufferList } = require('bl')

const bl = new BufferList()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append('hi')                     // bl will also accept & convert Strings
bl.append(Buffer.from('j'))
bl.append(Buffer.from([ 0x3, 0x4 ]))

console.log(bl.length) // 12

console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij'
console.log(bl.slice(3, 10).toString('ascii')) // 'defghij'
console.log(bl.slice(3, 6).toString('ascii'))  // 'def'
console.log(bl.slice(3, 8).toString('ascii'))  // 'defgh'
console.log(bl.slice(5, 10).toString('ascii')) // 'fghij'

console.log(bl.indexOf('def')) // 3
console.log(bl.indexOf('asdf')) // -1

// or just use toString!
console.log(bl.toString())               // 'abcdefghij\u0003\u0004'
console.log(bl.toString('ascii', 3, 8))  // 'defgh'
console.log(bl.toString('ascii', 5, 10)) // 'fghij'

// other standard Buffer readables
console.log(bl.readUInt16BE(10)) // 0x0304
console.log(bl.readUInt16LE(10)) // 0x0403

Give it a callback in the constructor and use it just like concat-stream:

const { BufferListStream } = require('bl')
const fs = require('fs')

fs.createReadStream('README.md')
  .pipe(BufferListStream((err, data) => { // note 'new' isn't strictly required
    // `data` is a complete Buffer object containing the full data
    console.log(data.toString())
  }))

Note that when you use the callback method like this, the resulting data parameter is a concatenation of all Buffer objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the callback method and just listen to 'end' instead, like a standard Stream.

Or to fetch a URL using hyperquest (should work with request and even plain Node http too!):

const hyperquest = require('hyperquest')
const { BufferListStream } = require('bl')

const url = 'https://raw.github.com/rvagg/bl/master/README.md'

hyperquest(url).pipe(BufferListStream((err, data) => {
  console.log(data.toString())
}))

Or, use it as a readable stream to recompose a list of Buffers to an output source:

const { BufferListStream } = require('bl')
const fs = require('fs')

var bl = new BufferListStream()
bl.append(Buffer.from('abcd'))
bl.append(Buffer.from('efg'))
bl.append(Buffer.from('hi'))
bl.append(Buffer.from('j'))

bl.pipe(fs.createWriteStream('gibberish.txt'))

API


new BufferList([ Buffer | Buffer array | BufferList | BufferList array | String ])

No arguments are required for the constructor, but you can initialise the list by passing in a single Buffer object or an array of Buffer objects.

new is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with:

const { BufferList } = require('bl')
const bl = BufferList()

// equivalent to:

const { BufferList } = require('bl')
const bl = new BufferList()

BufferList.isBufferList(obj)

Determines if the passed object is a BufferList. It will return true if the passed object is an instance of BufferList or BufferListStream and false otherwise.

N.B. this won't return true for BufferList or BufferListStream instances created by versions of this library before this static method was added.


bl.length

Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list.


bl.append(Buffer | Buffer array | BufferList | BufferList array | String)

append(buffer) adds an additional buffer or BufferList to the internal list. this is returned so it can be chained.


bl.get(index)

get() will return the byte at the specified index.


bl.indexOf(value[, byteOffset][, encoding])

get() will return the byte at the specified index. indexOf() method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present.


bl.slice([ start, [ end ] ])

slice() returns a new Buffer object containing the bytes within the range specified. Both start and end are optional and will default to the beginning and end of the list respectively.

If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer.


bl.shallowSlice([ start, [ end ] ])

shallowSlice() returns a new BufferList object containing the bytes within the range specified. Both start and end are optional and will default to the beginning and end of the list respectively.

No copies will be performed. All buffers in the result share memory with the original list.


bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])

copy() copies the content of the list in the dest buffer, starting from destStart and containing the bytes within the range specified with srcStart to srcEnd. destStart, start and end are optional and will default to the beginning of the dest buffer, and the beginning and end of the list respectively.


bl.duplicate()

duplicate() performs a shallow-copy of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call consume() or pipe() and still keep the original list.Example:

var bl = new BufferListStream()

bl.append('hello')
bl.append(' world')
bl.append('\n')

bl.duplicate().pipe(process.stdout, { end: false })

console.log(bl.toString())

bl.consume(bytes)

consume() will shift bytes off the start of the list. The number of bytes consumed don't need to line up with the sizes of the internal Buffers—initial offsets will be calculated accordingly in order to give you a consistent view of the data.


bl.toString([encoding, [ start, [ end ]]])

toString() will return a string representation of the buffer. The optional start and end arguments are passed on to slice(), while the encoding is passed on to toString() of the resulting Buffer. See the Buffer#toString() documentation for more information.


bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readBigInt64BE(), bl.readBigInt64LE(), bl.readBigUInt64BE(), bl.readBigUInt64LE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8()

All of the standard byte-reading methods of the Buffer interface are implemented and will operate across internal Buffer boundaries transparently.

See the Buffer documentation for how these work.


new BufferListStream([ callback | Buffer | Buffer array | BufferList | BufferList array | String ])

BufferListStream is a Node Duplex Stream, so it can be read from and written to like a standard Node stream. You can also pipe() to and from a BufferListStream instance.

The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the bl instance, when bl.end() is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is chunky, such as a network stream.

Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single Buffer object or an array of Buffer object.

new is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with:

const { BufferListStream } = require('bl')
const bl = BufferListStream()

// equivalent to:

const { BufferListStream } = require('bl')
const bl = new BufferListStream()

N.B. For backwards compatibility reasons, BufferListStream is the default export when you require('bl'):

const { BufferListStream } = require('bl')
// equivalent to:
const BufferListStream = require('bl')

Contributors

bl is brought to you by the following hackers:

License & copyright

Copyright (c) 2013-2019 bl contributors (listed above).

bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.

More Repositories

1

through2

Tiny wrapper around Node streams2 Transform to avoid explicit subclassing noise
JavaScript
1,894
star
2

node-worker-farm

Distribute processing tasks to child processes with an über-simple API and baked-in durability & custom concurrency options.
JavaScript
1,744
star
3

github-webhook-handler

Node.js web handler / middleware for processing GitHub Webhooks
JavaScript
783
star
4

bole

A tiny JSON logger
JavaScript
265
star
5

nodei.co

nodei.co - Node.js badges, that's all
JavaScript
258
star
6

archived-morkdown

A simple Markdown editor
JavaScript
245
star
7

node-errno

libuv errno details exposed
JavaScript
244
star
8

archived-dnt

Docker Node Tester
Shell
222
star
9

ghauth

Create and load persistent GitHub authentication tokens for command-line apps
JavaScript
184
star
10

archived-node-libssh

A Low-level Node.js binding for libssh
C++
132
star
11

archived-traversty

Headache-free DOM collection management and traversal
JavaScript
131
star
12

github-webhook

A flexible web server for reacting GitHub Webhooks
JavaScript
114
star
13

archived-node-pygmentize-bundled

A simple wrapper around Python's Pygments code formatter, with Pygments bundled
HTML
95
star
14

archived-lmdb

C++
85
star
15

jsonist

JSON over HTTP: A simple wrapper around hyperquest for dealing with JSON web APIs
JavaScript
66
star
16

isstream

Determine if an object is a Node.js Stream
JavaScript
63
star
17

polendina

Non-UI browser testing for JavaScript libraries from the command-line
JavaScript
63
star
18

archived-CAPSLOCKSCRIPT

JAVASCRIPT: T-H-E L-O-U-D P-A-R-T-S
JavaScript
60
star
19

archived-gfm2html

Convert a GitHub style Markdown file to HTML, complete with inline CSS
CSS
49
star
20

archived-node-level-session

A very fast and persistent web server session manager backed by LevelDB
JavaScript
49
star
21

cborg

fast CBOR with a focus on strictness
JavaScript
44
star
22

csv2

A Node Streams2 CSV parser
JavaScript
38
star
23

archived-pangyp

Node.js and io.js native addon build tool a (hopefully temporary) fork of TooTallNate/node-gyp
Python
38
star
24

archived-tsml

ES6 template string tag for multi-line cleaning - squash multi-line strings into a single line
JavaScript
37
star
25

archived-node-level-mapped-index

JavaScript
35
star
26

archived-node-rsz

An image resizer for Node.js
JavaScript
34
star
27

iamap

An Immutable Asynchronous Map
JavaScript
31
star
28

archived-servertest

A simple HTTP server testing tool
JavaScript
30
star
29

node-du

A simple JavaScript implementation of `du -sb`
JavaScript
29
star
30

archived-node-brucedown

A near-perfect GitHub style Markdown to HTML converter
JavaScript
29
star
31

rpi-newer-crosstools

Newer cross-compiler toolchains than are available @ https://github.com/raspberrypi/tools
C++
28
star
32

list-stream

Collect chunks / objects from a readable stream, write obejcts / chunks to a writable stream
JavaScript
27
star
33

archived-prr

JavaScript
26
star
34

archived-npm-explicit-deps

Say goodbye to fickle `~` and `^` semver ranges
JavaScript
26
star
35

ghissues

A node library to interact with the GitHub issues API
JavaScript
25
star
36

archived-string_decoder

Moved to https://github.com/nodejs/string_decoder
23
star
37

archived-node-sz

A Node.js utility for determining the dimensions of an image
JavaScript
23
star
38

js-ipld-hashmap

An associative array Map-type data structure for very large, distributed data sets built on IPLD
JavaScript
23
star
39

delayed

A collection of JavaScript helper functions for your functions, using setTimeout() to delay and defer.
JavaScript
22
star
40

archived-npm-publish-stream

A Node.js ReadableStream that emits data for each module published to npm
JavaScript
21
star
41

ghutils

A collection of utility functions for dealing with the GitHub API
JavaScript
20
star
42

archived-node-require-subvert

Yet another `require()` subversion library for mocking & stubbing
JavaScript
19
star
43

archived-level-ttl-cache

A pass-through cache for arbitrary objects or binary data using LevelDB, expired by a TTL
JavaScript
18
star
44

archived-level-spaces

Namespaced LevelUP instances
JavaScript
18
star
45

archived-node-generic-session

A generic web server session manager for use with any storage back-end
JavaScript
18
star
46

node-boganipsum

Node.js Lorem Ipsum ... Bogan Style!
JavaScript
17
star
47

archived-externr

Provide a plug-in mechanism for your JavaScript objects, exposing their inmost secrets
JavaScript
17
star
48

archived-npm-publish-notify

Desktop notifications on npm publish events
JavaScript
15
star
49

archived-new-contributors

Check a GitHub repository for new contributors
JavaScript
15
star
50

archived-iojs-tools

A collection of utilities I use to help with managing io.js business
HTML
15
star
51

archived-blorg

Flexible static blog generator
JavaScript
15
star
52

archived-node-simple-bufferstream

Turn a Node.js Buffer into a ReadableStream
JavaScript
14
star
53

archived-node-slow-stream

A throttleable stream, for working in the slow-lane
JavaScript
13
star
54

archived-node-crp

An image cropper for Node.js
JavaScript
13
star
55

archived-brtapsauce

Browserify TAP test runner for SauceLabs
JavaScript
12
star
56

archived-node-thmb

An image thumbnailer for Node.js
JavaScript
12
star
57

npm-download-counts

Fetch package download counts for packages from the npm registry
JavaScript
12
star
58

archived-nodei.co-chrome

Chrome extension to display nodei.co npm badges on GitHub README files for Node.js packages
JavaScript
11
star
59

ghrepos

A node library to interact with the GitHub repos API
JavaScript
11
star
60

archived-level-updown

LevelDOWN backed by LevelUP
JavaScript
11
star
61

archived-node-level-multiply

Make your LevelUP get(), put() and del() accept multiples keys & values.
JavaScript
11
star
62

ghteams

Node library to interact with the GitHub teams API
JavaScript
10
star
63

ghusers

A node library to interact with the GitHub users API
JavaScript
10
star
64

js-datastore-zipcar

An implementation of a Datastore (https://github.com/ipfs/interface-datastore) for IPLD blocks that operates on ZIP files
JavaScript
9
star
65

archived-bustermove

JavaScript
9
star
66

node-version-data

Load all Node.js and io.js versions and metadata about them
JavaScript
8
star
67

node-fd

File descriptor manager
JavaScript
8
star
68

archived-sanever

A saner semver parser
JavaScript
7
star
69

js-bitcoin-block

A Bitcoin block interface and decoder for JavaScript
JavaScript
7
star
70

ghpulls

A node library to interact with the GitHub pull requests API
JavaScript
7
star
71

testmark.js

Language-agnostic test fixtures in Markdown
JavaScript
6
star
72

campjs-2013-learn-you-node

CSS
5
star
73

archived-quantities

JavaScript library for physical quantity representation and conversion
JavaScript
5
star
74

jsdoc4readme

Generate an API section for a README.md from inline JSDocs
JavaScript
5
star
75

archived-package-use

Use the nodei.co Node.js package download count API to create CSV data on package use
JavaScript
5
star
76

archived-node-ssbl

Super-simple blog loader. Load markdown formatted blog files from a folder as a handy data structure for rendering
JavaScript
5
star
77

mkfiletree

Make a tree of files and directories by from data defined in an object
JavaScript
5
star
78

readfiletree

Deserialize an file/directory tree into object form
JavaScript
4
star
79

archived-check-python

Check for Python on the current system and return the value
JavaScript
4
star
80

archived-colors-tmpl

Simple templating for applying colors.js to strings
JavaScript
4
star
81

bit-sequence

Turn an arbitrary sequence of bits from a byte array and turn it into an integer
JavaScript
4
star
82

nodei.co-npm-dl-api

API server to manage the npm downloads counts and rankings for nodei.co
JavaScript
3
star
83

archived-node-downer-rangedel

A native LevelDOWN plugin providing a rangeDel() method
JavaScript
3
star
84

blake2-node

Node.js BLAKE2 addon
C
3
star
85

js-ipld-schema-describer

Provide an object that suits the Data Model and get a naive IPLD Schema description of it.
JavaScript
3
star
86

nodei.co-pkginfo-api

API server to manage the npm package info data for nodei.co
JavaScript
3
star
87

bsplit2

A Node.js binary transform stream splitting chunks by newline characters
JavaScript
3
star
88

archived-npm-download-db

A local store containing npm download counts for all packages, able to provide rankings
JavaScript
3
star
89

gitexec

A specialised child process spawn for `git` commands
JavaScript
3
star
90

js-fil-utils

Miscellaneous JavaScript Filecoin proofs utilities
JavaScript
3
star
91

archived-kappa-bridge

A bridge for certificate-authenticated npm connections to Kappa registries
JavaScript
3
star
92

node-ci-containers

Dockerfile
2
star
93

r.va.gg

HTML
2
star
94

lxjs2013

JavaScript Databases II
CSS
2
star
95

archived-simpledb2level

Extract complete (or partial / incremental) SimpleDB data to a local LevelDB
JavaScript
2
star
96

iavector

An Immutable Asynchronous Vector
JavaScript
2
star
97

js-bitcoin-extract

Tools to work with the Bitcoin blockchain (and IPLD)
JavaScript
2
star
98

kasm

A WASM thing in Rust that's probably not what you're looking for
Rust
2
star
99

js-ipld-schema-validator

Build fast and strict JavaScript object form validators using IPLD Schemas
JavaScript
2
star
100

js-ipld-vector

A JavaScript implementation of the IPLD Vetor specification
JavaScript
2
star