ForbesLindesay / browserify-middleware

express middleware for browserify, done right
http://browserify.org
MIT License
381 stars 66 forks source link

Example usage with req, res, next #127

Closed zeke closed 5 years ago

zeke commented 5 years ago

Hi @ForbesLindesay,

Thanks for creating this module! I'm using is successfully but am having trouble catching errors when there's a problem in my browser code. The README says:

Simply pass in req res, and a callback that will only be called in the event of an error.

But I can find no examples of this style of usage. All the examples I see have a function signature like (entry, options), not (req, res, next).

How can I use this module in a way that allows me to capture errors and pass them to a next handler?

ForbesLindesay commented 5 years ago

If you're using express, you can follow the normal express approach to handling errors, as this is middleware. If you're not using express:

const {createServer} = require('http');

createServer((req, res) => browserifyMiddleware(path, options)(req, res, err => {...})
zeke commented 5 years ago

Thanks for the reply. I am using Express, but I don't want to use the middleware style where you pass a path as the first argument:

app.use('/js', browserify(__dirname + '/client/dir'));

I want instead to write a custom middleware, but can't seem to figure out how to make that work:

function myMiddleware(req, res, next) {
   if (req.path !== '/script.js') return next()

   // browserify-middleware goes here
}

app.use(myMiddleware)

Is this use case supported? Thanks for your patience, and thanks again for writing this library. Nice to not have to think about caching and minification, production vs development, etc.

ForbesLindesay commented 5 years ago
const br = browserifyMiddleware(path, options)
function myMiddleware(req, res, next) {
   if (req.path !== '/script.js') return next()

   // browserify-middleware goes here
  br(req, res, next);
}

This is just JavaScript, it doesn't really have anything to do with this library. You can do that with any express middleware.