cssmin.js in windows shell

October 29th, 2010. Tagged: CSS, JavaScript, performance

JavaScript can run virtually anywhere, including as a windows exe and the windows command line.

Say you have a JavaScript function foo()

function foo(input) {
  var output = input;
  // .. unicorns
  return output;
}

In order to make this a windows shell script you add at the and a way to read standard input and then write to the standard output:

(function () {
 
    var input  = WScript.StdIn.ReadAll(),
        output = foo(input);
 
    WScript.StdOut.Write(output);
 
}());

Then you run this script, say foo.js, like:

$ cscript foo.js < input.txt

And it prints the output to the console.

If you want to read and print the code of foo.js itself you go:

$ cscript foo.js < foo.js
Microsoft (R) Windows Script Host Version 5.7
Copyright (C) Microsoft Corporation. All rights reserved.

function foo(input) {
  var output = input;
...

You can remove this "Microsoft (R) Windows..." stuff with //NoLogo parameter:

$ cscript //NoLogo foo.js < foo.js
function foo(input) {
  var output = input;
...

CSSMin.JS

Alrighty, going back to the title of the post.

CSSMin.js is a port of YUICompressor's CSS minifier (source, hosted tool). Now adding a few lines at the end makes a windows shell script:

(function () {
 
    var src = WScript.StdIn.ReadAll();
 
    if (!src) {
        // help!
        WScript.StdOut.WriteLine("cscript //NoLogo cssmin.js < in.css > out.css");
        return;
    }
 
    WScript.StdOut.Write(YAHOO.compressor.cssmin(src));
 
}());

Download it here.

Use it like:

$ cscript //NoLogo cssmin.js < in.css > out.css

Don't forget the //NoLogo or you'll end up with "Microsoft..." in your minified files

Random observation: "dude"[0] === "d" in most JS environments but is undefined in WSH (Windows Scripting Host). So "dude".substring(0, 1)

Tell your friends about this post: Facebook, Twitter, Google+

5 Responses

  1. Lovely tool. I used your OMG tool for quick CSS compression, but this is much more old school (I like it). Other thing, I like the personalization you can comment the parts of CSSMin.js that don’t want to be processed and you can build your own CSSMin.js.

    Keep up the good work!

  2. Never occurred to me try this. Excellent. Have you tried (‘foo’).chartAt(0) == ‘f’?

  3. I never used cscript before. Neat. I’ll have to see what js command line tools are out there for Linux and compare. Ever used one of them?

  4. [...] cssmin.js in windows shell (phpied.com) [...]

  5. This Article very useful. It’s a good inspiration. I can Bookmark it. Thank you.

Leave a Reply