Lazy Node.js Streams

1.0.1 · abandoned · verified Sun Apr 19

lazystream is a Node.js utility library designed to address the "too many open files" (EMFILE) error by creating readable and writable streams on demand. Instead of eagerly opening file handles or other resources upon instantiation, it wraps stream creation functions, deferring the actual stream initialization until the stream is actively accessed (e.g., read from, written to, or piped). The current stable version is 1.0.1, released in 2016. The package provides `lazystream.Readable` and `lazystream.Writable` classes, which internally extend Node's `stream.PassThrough` by relying on `readable-stream@2.x` for a stable Streams3 API implementation. This approach allows developers to pass around stream proxies without immediate resource allocation, offering a simple, callback-based mechanism to encapsulate stream creation logic. However, the package is no longer actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create lazy readable and writable streams using `lazystream`, deferring the actual file opening until data is piped, and then cleans up the temporary files.

const lazystream = require('lazystream');
const fs = require('fs');
const path = require('path');

// Create a dummy file for reading
const inputFile = path.join(__dirname, 'input.txt');
fs.writeFileSync(inputFile, 'Hello, lazy stream!');

// Define the output file
const outputFile = path.join(__dirname, 'output.txt');

console.log('Creating lazy streams...');
// Create a lazy readable stream
const lazyReadable = new lazystream.Readable(function () {
  console.log('  -> Actually opening read stream now.');
  return fs.createReadStream(inputFile);
});

// Create a lazy writable stream
const lazyWritable = new lazystream.Writable(function () {
  console.log('  -> Actually opening write stream now.');
  return fs.createWriteStream(outputFile);
});

console.log('Lazy streams instantiated, but file handles are not yet open.');

// Pipe the lazy readable to the lazy writable
lazyReadable.pipe(lazyWritable)
  .on('finish', () => {
    console.log('Piping finished. Content written to output.txt');
    const content = fs.readFileSync(outputFile, 'utf8');
    console.log('Output file content:', content);
    // Clean up
    fs.unlinkSync(inputFile);
    fs.unlinkSync(outputFile);
  })
  .on('error', (err) => {
    console.error('Stream error:', err);
    // Clean up in case of error
    if (fs.existsSync(inputFile)) fs.unlinkSync(inputFile);
    if (fs.existsSync(outputFile)) fs.unlinkSync(outputFile);
  });

console.log('Piping operation initiated. Streams will open on first data access.');

view raw JSON →