2

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!

Dragunov
  • 975
  • 1
  • 7
  • 14

1 Answers1

1

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));
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95
  • One issue that I faced with above code is subsequent requests for same file turn up empty HTTP 200 response. Am trying to see what could be the issue, also would it be better to process the entire file at once, giving better chance at compression ? – Dragunov Jan 01 '18 at 19:59
  • Whoopsie, fixed the code example. You have to create a new minify transform with every request. – Patrick Hund Jan 01 '18 at 20:13
  • Works beautifully! – Dragunov Jan 02 '18 at 07:26