Transform the first chunk in a stream
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
.editorconfig add XO and fix code style Sep 20, 2015
.gitattributes init May 25, 2014
.gitignore init May 25, 2014
.travis.yml add XO and fix code style Sep 20, 2015
index.js Correct spelling mistake (#4) Sep 2, 2017
license init May 25, 2014
package.json bump dev deps Nov 14, 2015 readme tweaks Nov 23, 2015
test.js bump dev deps Nov 14, 2015

first-chunk-stream Build Status

Buffer and transform the n first bytes of a stream


$ npm install --save first-chunk-stream


const fs = require('fs');
const getStream = require('get-stream');
const firstChunkStream = require('first-chunk-stream');

// unicorn.txt => unicorn rainbow
const stream = fs.createReadStream('unicorn.txt')
	.pipe(firstChunkStream({chunkLength: 7}, (err, chunk, enc, cb) => {
		if (err) {

		cb(null, chunk.toUpperCase());

getStream(stream).then(data => {
	if (data.length < 7) {
		throw new Error(`Couldn't get the minimum required first chunk length`);

	//=> 'UNICORN rainbow'


firstChunkStream([options], transform)

Returns a FirstChunkStream instance.


The options object is passed to the Duplex stream constructor allowing you to customize your stream behavior. In addition you can specify the following option:


Type: number

How many bytes you want to buffer.

transform(err, chunk, encoding, callback)

Type: function

The function that gets the required options.chunkLength bytes.

Note that the buffer can have a smaller length than the required one. In that case, it will be due to the fact that the complete stream contents has a length less than the options.chunkLength value. You should check for this yourself if you strictly depend on the length.


MIT © Sindre Sorhus