asynchronous javascript, but not ajax, get ready to tune out now...
I have two pieces of middleware in my nodejs 1 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-less to convert .less 2 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 nodejs 1 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 github.com/MartinodF/connect-less
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](/wiki/#nodejs) server.[js](/wiki/#javascript)
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( );
http.[js](/wiki/#javascript):520
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](/wiki/#javascript):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( );
Node: Javascript (programming language of the web) on the server side.
javascript: Programming language of the internets, mostly how I make my living.
⬅️ I think we'll go to Chambers for lunch tomorrow :: TRON in 219 bytes of javascript ➡️
Paul Clarkeʼs weblog - I live in Hythe in the deep South. Married and father to two, I am a full-stack web developr, + I do js / Node, some ruby, other languages etc. I like pubbing, running, restaurants, home-automation and other diy jiggery-pokery, history, tree stuff, Television, squirrels, pirates, lego, and time travel.