How to pipe requests into clean-css in nodejs?

320 views Asked by At

I'm trying to pipe request output into clean-css to minify and then provide it as a response. The example app in question is built on restify.

Sample Objective Code :

var url = "http://www.example.com/css/style.css";
request.get(url).pipe(minify()).pipe(res);

How can I define the minify() function to accept stream and return one. I've tried dozens of packages, none worked. Help would be much appreciated!

1

There are 1 answers

3
Patrick Hund On BEST ANSWER

You can create a Transform stream. It gets the CSS code from the stream created by request.get, does the minification magic and returns the minified CSS.

Here's a working example:

const restify = require('restify');
const request = require('request');
const { Transform } = require('stream');
const CleanCSS = require('clean-css');

const server = restify.createServer();
const cleanCss = new CleanCSS();
const url = 'http://www.example.com/css/style.css';

function createMinifyTransform() {
    return new Transform({
        transform(chunk, encoding, callback) {
            const output = cleanCss.minify(chunk.toString());
            this.push(output.styles);
            callback();
        }
    });
}

function respond(req, res) {
    request
        .get(url)
        .pipe(createMinifyTransform())
        .pipe(res);
}

server.get('/', respond);

server.listen(8080, () => console.log('%s listening at %s', server.name, server.url));