Trough Middleware Pipeline

2.2.0 · active · verified Wed Apr 22

`trough` is a lightweight, promise-aware middleware utility designed for building flexible processing pipelines in JavaScript and TypeScript environments. Currently at version 2.2.0, it is actively maintained with a consistent release cadence for minor improvements and bug fixes, typically addressing specific use cases or compatibility enhancements. Unlike some traditional middleware solutions, `trough` allows each stage of the pipeline to modify the input for subsequent stages and seamlessly integrates both synchronous and asynchronous functions, including those that return promises or use Node.js-style callbacks. Its core differentiator lies in its minimal API and explicit control over data flow, making it suitable for scenarios like plugin systems or data transformation pipelines. It is an ESM-only package, targeting modern Node.js (v16+) and browser environments via `esm.sh`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating a `trough` pipeline with both synchronous and asynchronous (callback and Promise-based) middleware functions, showing how data flows and errors are handled.

import fs from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import {trough} from 'trough'

const pipeline = trough()
  .use(function (fileName) {
    console.log('Checking… ' + fileName)
  })
  .use(function (fileName) {
    return path.join(process.cwd(), fileName)
  })
  .use(function (filePath, next) {
    // Asynchronous middleware uses a callback
    fs.stat(filePath, function (error, stats) {
      next(error, {filePath, stats})
    })
  })
  .use(async function (ctx) {
    // Or use async/await for Promises
    if (ctx.stats.isFile()) {
      return new Promise((resolve, reject) => {
        fs.readFile(ctx.filePath, (err, data) => {
          if (err) reject(err); else resolve(data)
        })
      })
    } else {
      throw new Error('Expected file')
    }
  })

// Example usage with a valid file and an invalid path
pipeline.run('readme.md', console.log)
pipeline.run('node_modules', console.log)

view raw JSON →