• Stars
    star
    230
  • Rank 174,053 (Top 4 %)
  • Language
    JavaScript
  • License
    The Unlicense
  • Created almost 14 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Readable and Writable Streams that use backing Buffers.

Node Stream Buffers

Build Status npm

!! Consider using Node 16+ Utility Consumers rather than this library. !!

Simple Readable and Writable Streams that use a Buffer to store received data, or for data to send out. Useful for test code, debugging, and a wide range of other utilities.

npm install stream-buffers --save

Usage

To use the stream buffers in your module, simply import it and away you go.

var streamBuffers = require('stream-buffers');

WritableStreamBuffer

WritableStreamBuffer implements the standard stream.Writable interface. All writes to this stream will accumulate in an internal Buffer. If the internal buffer overflows it will be resized automatically. The initial size of the Buffer and the amount in which it grows can be configured in the constructor.

var myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({
	initialSize: (100 * 1024),   // start at 100 kilobytes.
	incrementAmount: (10 * 1024) // grow by 10 kilobytes each time buffer overflows.
});

The default initial size and increment amount are stored in the following constants:

streamBuffers.DEFAULT_INITIAL_SIZE      // (8 * 1024)
streamBuffers.DEFAULT_INCREMENT_AMOUNT  // (8 * 1024)

Writing is standard Stream stuff:

myWritableStreamBuffer.write(myBuffer);
// - or -
myWritableStreamBuffer.write('\u00bd + \u00bc = \u00be', 'utf8');

You can query the size of the data being held in the Buffer, and also how big the Buffer's max capacity currently is:

myWritableStreamBuffer.write('ASDF');
streamBuffers.size();     // 4.
streamBuffers.maxSize();  // Whatever was configured as initial size. In our example: (100 * 1024).

Retrieving the contents of the Buffer is simple.

// Gets all held data as a Buffer.
myWritableStreamBuffer.getContents();

// Gets all held data as a utf8 string.
myWritableStreamBuffer.getContentsAsString('utf8');

// Gets first 5 bytes as a Buffer.
myWritableStreamBuffer.getContents(5);

// Gets first 5 bytes as a utf8 string.
myWritableStreamBuffer.getContentsAsString('utf8', 5);

Care should be taken when getting encoded strings from WritableStream, as it doesn't really care about the contents (multi-byte characters will not be respected).

Destroying or ending the WritableStream will not delete the contents of Buffer, but will disallow any further writes.

myWritableStreamBuffer.write('ASDF');
myWritableStreamBuffer.end();
myWritableStreamBuffer.getContentsAsString(); // -> 'ASDF'

ReadableStreamBuffer

ReadableStreamBuffer implements the standard stream.Readable, but can have data inserted into it. This data will then be pumped out in chunks as readable events. The data to be sent out is held in a Buffer, which can grow in much the same way as a WritableStreamBuffer does, if data is being put in Buffer faster than it is being pumped out.

The frequency in which chunks are pumped out, and the size of the chunks themselves can be configured in the constructor. The initial size and increment amount of internal Buffer can be configured too. In the following example 2kb chunks will be output every 10 milliseconds:

var myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({
	frequency: 10,   // in milliseconds.
	chunkSize: 2048  // in bytes.
});

Default frequency and chunk size:

streamBuffers.DEFAULT_CHUNK_SIZE  // (1024)
streamBuffers.DEFAULT_FREQUENCY   // (1)

Putting data in Buffer to be pumped out is easy:

myReadableStreamBuffer.put(aBuffer);
myReadableStreamBuffer.put('A String', 'utf8');

Chunks are pumped out via standard stream.Readable semantics. This means you can use the old streams1 way:

myReadableStreamBuffer.on('data', function(data) {
  // streams1.x style data
  assert.isTrue(data instanceof Buffer);
});

Or the streams2+ way:

myReadableStreamBuffer.on('readable', function(data) {
  var chunk;
  while((chunk = myReadableStreamBuffer.read()) !== null) {
    assert.isTrue(chunk instanceof Buffer);
  }
});

Because ReadableStreamBuffer is simply an implementation of stream.Readable, it implements pause / resume / setEncoding / etc.

Once you're done putting data into a ReadableStreamBuffer, you can call stop() on it.

myReadableStreamBuffer.put('the last data this stream will ever see');
myReadableStreamBuffer.stop();

Once the ReadableStreamBuffer is done pumping out the data in its internal buffer, it will emit the usual end event. You cannot write any more data to the stream once you've called stop() on it.

Disclaimer

Not supposed to be a speed demon, it's more for tests/debugging or weird edge cases. It works with an internal buffer that it copies contents to/from/around.

Contributors

Thank you to all the wonderful contributors who have kept this package alive throughout the years.

License

node-stream-buffer is free and unencumbered public domain software. For more information, see the accompanying UNLICENSE file.

More Repositories

1

node-google-spreadsheets

Google Spreadsheet Data API for node.js & the browser
JavaScript
184
star
2

logstash-output-kinesis

A Kinesis output plugin for Logstash that uses KPL.
Ruby
59
star
3

node-fastcgi-stream

FastCGI protocol implementation.
JavaScript
28
star
4

node-stream-splitter

Stream splitting. Like a boss.
CoffeeScript
25
star
5

rmarsh

Ruby Marshal 4.8 encoder/decoder in Golang. Why? Who knows.
Go
15
star
6

node-fastcgi-application

Run Node under a FCGI process manager.
JavaScript
12
star
7

home-cluster

HCL
10
star
8

node-etcd-leader

Etcd leader election implementation for Node.js
JavaScript
8
star
9

deathbycaptcha.js

DeathByCaptcha for Node.js
CoffeeScript
7
star
10

srs.js

Javascript implementation of Sender Rewriting Scheme.
JavaScript
7
star
11

oxideboy

Yet another Gameboy emulator written in Rust.
Rust
5
star
12

node-clusterphone

Node.js cluster messaging made easy.
JavaScript
5
star
13

node-debian-control-parser

Debian control data parser.
CoffeeScript
5
star
14

NodeServ

Pure-node web server.
JavaScript
5
star
15

gud-gadget

Rust
5
star
16

phrog

🐸 Mobile device greeter
C
5
star
17

node-traceurified-module

JavaScript
4
star
18

jnntp

NNTP client for Java (using Netty).
Java
4
star
19

javastorm

Netstorm bot: Botsy source + JavaStorm (incomplete rewrite of NS in Java... no idea why)
Java
4
star
20

go-dash-javadocset

Go implementation of Kapeli/javadocset
Go
3
star
21

appdb

CoffeeScript
3
star
22

node-duplex-stream

Composable Stream abstraction.
JavaScript
3
star
23

asyncevents

Extension to EventEmitter to facilitate asynchronous firing of events, and asynchronous handling of those events.
JavaScript
3
star
24

heroku-buildpack-brunch

Buildpack for apps that use Brunch.io
3
star
25

site2go

Java
2
star
26

citycycledata

JavaScript
2
star
27

gwt-mce

TinyMCE API bindings for GWT.
Java
2
star
28

socketio-cluster

Node cluster support for Socket.IO 1.0
JavaScript
2
star
29

cricos_scrape

CRICOS (http://cricos.deewr.gov.au/) database scraper using Scrapy.
Python
2
star
30

csgo-rank-sniffer

Sniff player ranks out of a demo file
Go
2
star
31

workstation-config

Dockerfile
2
star
32

lk-msm8916

C
2
star
33

archlinux-msm8916

Shell
2
star
34

icondb

C
1
star
35

hcloud-fip-k8s

Go
1
star
36

personal-infrastructure

1
star
37

cork-blog-jekyll

Jekyll-like blog handler for Cork
CoffeeScript
1
star
38

samcday.github.io

CSS
1
star
39

freshmine

Redmine -> Freshbooks integration
Python
1
star
40

gwt-stickywidget

Java
1
star
41

cork

Pluggable static site generator, powered by Node.js
CoffeeScript
1
star
42

cork-content-markdown

Markdown content plugin for Cork.
CoffeeScript
1
star
43

example-cork

Example site using Cork.
CoffeeScript
1
star
44

bincrawl

JavaScript
1
star
45

cork-layout-coffeekup

CoffeeKup layouts for Cork.
CoffeeScript
1
star
46

hotpotato

Hand-off HTTP connections between Node cluster workers.
JavaScript
1
star
47

node-powerdns

PowerDNS REST client for Node.js
JavaScript
1
star
48

gwt-functionproxy

Pass GWT Java callbacks to Javascript with ease.
Java
1
star
49

usb-kvm

Rust
1
star
50

grails-binders

Custom data binders made easy!
Groovy
1
star
51

mailbutler

Personal email proxy.
Ruby
1
star
52

couchdb-json-logs

Raw CouchDB log lines go in. JSON log records go out.
JavaScript
1
star
53

elasticsearch-oomonster

Have you checked your closet for the OOMonster lately?
Java
1
star
54

cork-assets-less

LESS assets for Cork.
CoffeeScript
1
star
55

samcday.com.au-cork

samcday.com.au - Cork powered
CoffeeScript
1
star