Created
April 18, 2018 04:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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