Middleware Utils

1.0.0 · abandoned · verified Wed Apr 22

The `middleware-utils` package provides a compact collection of utility functions designed to streamline the creation and management of middleware in Node.js applications. It's particularly useful within build or templating ecosystems, such as `assemble`, where middleware often requires sequential or parallel execution. Key functionalities include `series` and `parallel` for controlling middleware flow, `error` and `handleError` for standardized error reporting, and `delims` for escaping and unescaping template delimiters. The package's current stable version is 1.0.0, originally released in 2017. Due to its age and lack of updates, it effectively has an abandoned release cadence. Its API is callback-based, reflecting the common asynchronous patterns of its era, and it lacks native support for modern JavaScript features like Promises or ES Modules.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `middleware-utils.series` to run multiple middleware functions sequentially within a simulated application context, and how to define custom middleware functions.

const utils = require('middleware-utils');

// Simulate an application object that can register middleware
const app = {
  _middleware: [],
  preRender: function(pattern, fn) {
    this._middleware.push({ pattern, fn });
  },
  // Simple handler to execute middleware
  handle: function(view, done) {
    const matchingFns = this._middleware.filter(m => view.name.match(m.pattern));
    if (matchingFns.length === 0) {
      return done(null, view);
    }

    const seriesRunner = utils.series(matchingFns.map(m => m.fn));
    seriesRunner(view, done);
  }
};

function createMiddleware(name) {
  return function(file, next) {
    console.log(`Executing middleware: ${name} for file: ${file.name}`);
    // Simulate async work
    setTimeout(() => next(), 50);
  };
}

// Register middleware using utils.series
app.preRender(/\.hbs$/, utils.series([
  createMiddleware('foo'),
  createMiddleware('bar'),
  createMiddleware('baz')
]));

// Register a single middleware
app.preRender(/\.txt$/, createMiddleware('text-processor'));

console.log('Starting middleware processing...');
app.handle({ name: 'template.hbs', content: '...' }, (err, result) => {
  if (err) {
    console.error('Error handling .hbs:', err);
  } else {
    console.log('Finished handling template.hbs.');
  }
});

app.handle({ name: 'document.txt', content: '...' }, (err, result) => {
  if (err) {
    console.error('Error handling .txt:', err);
  } else {
    console.log('Finished handling document.txt.');
  }
});

view raw JSON →