Blog2012 ≫ Middleware dependency in nodejs + express

asynchronous javascript, but not ajax, get ready to tune out now...

I have two pieces of middleware in my nodejs1 app, one depends on another. I thought this was possible, I've seen mention of the importance of ordering of your middleware, but the second does not wait for the first to complete. I'm using connect-less2 to convert .less3 to css where appropriate, but if the related less file for a requested css file does not exist, then instead of raising an error I want to request a remote file and create the .less file using that before continuing. I am aware the raison d'etre of nodejs1 is that everything is asynchronous, but I'm sure I've seen mention of the importance of the ordering of the middleware and how you can have this part dependent on that part.

My middleware is set up like this

   app.use( agentLess( { src: staticDir, debug: true } ));
   app.use( connectLess( { src: staticDir, debug: true } ));

My agentLess code (my own middleware) is mostly ripped off

In agentLess, next() is only passed as the callback to fs.writeFile() like so

fs.writeFile( src, output, 'utf8', next );

so what I want is only to go to the next middleware when the file is created, but from my logs I can see an error before that point:

node server.js 
Express server listening on port 3000 in development mode
[agent-less] rebuilding /stylesheets/WEB1.less
Error: ENOENT, no such file or directory '/stylesheets/WEB1.less'
[agent-less] writing 369 chars to /stylesheets/WEB1.less and then calling next( );
    throw new Error("Can't set headers after they are sent.");
Error: Can't set headers after they are sent.
    at ServerResponse.anonymous (http.js:520:11)

Is what I'm trying to do possible? Is the problem what I think it is? My first instinct was to replace connect-less.js with something that compiles .less files AND creates the .less file if it doesn't exist, but is there any way other than this to control the dependency?

UPDATE: Fixed it, I had a double callback at the end of my code, like this:

if ( err && 'ENOENT' === err.code ) {
  return build( src );
return next( );

where I originally had this:

if ( err && 'ENOENT' === err.code ) {
  build( src ); // dur would build and then call next( )...
return next( );

nodejs: Javascript (programming language of the internets) on the server side.

⬅️ :: ➡️

Paul Clarke's weblog - I live in A small town. Married to Clare and dad to 2, I am a full stack web developr, + I do javascript / Node, some ruby, python, php ect ect. I like pubbing, parkrun, restaurants, home automation + other diy jiggery-pokery, history, genealogy, TV, squirrels, pirates, lego, and time travel.