Skip to content

Instantly share code, notes, and snippets.

@ancms2600
Created April 18, 2018 04:00
Show Gist options
  • Save ancms2600/85238e39ba21dc292b0c16ef29aff2e9 to your computer and use it in GitHub Desktop.
Save ancms2600/85238e39ba21dc292b0c16ef29aff2e9 to your computer and use it in GitHub Desktop.
Express.js render Stylus .styl to .css every request; skips output file to local disk
// render .styl to .css every request; skips output file to local disk
app.use((req, res, next) => {
const stylus = require('stylus');
const join = require('path').join;
const src = join(__dirname, '/../public');
const url = require('url');
const fs = require('fs');
if ('GET' !== req.method && 'HEAD' !== req.method) return next();
const path = url.parse(req.url).pathname;
if (!/\.css$/.test(path)) return next();
const stylusPath = join(src, path.replace('.css', '.styl'));
const error = err => next('ENOENT' === err.code ? null : err);
fs.readFile(stylusPath, 'utf8', (err, str) => {
if (err) return error(err);
stylus(str)
.set('filename', stylusPath)
.render((err, css) => {
if (err) return error(err);
res.type('css').end(css);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment