Created
July 12, 2011 23:41
-
-
Save tiff/1079436 to your computer and use it in GitHub Desktop.
Easily compile your javascript files via node.js on the command line
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
// 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