Skip to content

Instantly share code, notes, and snippets.

@tiff
Created July 12, 2011 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiff/1079436 to your computer and use it in GitHub Desktop.
Save tiff/1079436 to your computer and use it in GitHub Desktop.
Easily compile your javascript files via node.js on the command line
// Minify and compile your javascript via node.js on the command line
//
// Usage:
// node minify.js "my_script.js"
var script = process.argv[2],
http = require("http"),
queryString = require("querystring"),
fs = require("fs");
if (!script) {
throw "No script url given";
}
function post(code, callback) {
var postData = queryString.stringify({
compilation_level: "SIMPLE_OPTIMIZATIONS",
output_format: "text",
output_info: "compiled_code",
warning_level: "QUIET",
js_code: code
});
var postOptions = {
host: "closure-compiler.appspot.com",
port: "80",
path: "/compile",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": postData.length
}
};
var request = http.request(postOptions, function(response) {
var responseText = [];
response.setEncoding("utf8");
response.on("data", function(data) {
responseText.push(data);
});
response.on("end", function() {
callback(responseText.join(""));
});
});
// Post the data
request.write(postData);
request.end();
}
function readFile(filePath, callback) {
fs.readFile(filePath, "utf-8", function (err, data) {
if (data) {
callback(data);
} else {
console.log("The script is empty?!");
process.exit(-1);
}
});
}
function writeFile(filePath, data, callback) {
fs.writeFile(filePath, data, "utf-8", callback);
}
console.log("Reading file ...");
readFile(script, function(code) {
console.log("Contacting Google Closure Compiler API ...");
post(code, function(code) {
console.log("Writing file ...");
var output = script.replace(/\.js/, ".min.js");
writeFile(output, code, function() {
console.log("Done. Your minified script can be found here: " + output);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment