2 * @alias ProtoBuf.Util
\r
5 ProtoBuf.Util = (function() {
\r
9 * ProtoBuf utilities.
\r
10 * @exports ProtoBuf.Util
\r
16 * Flag if running in node or not.
\r
22 typeof process === 'object' && process+'' === '[object process]' && !process['browser']
\r
26 * Constructs a XMLHttpRequest object.
\r
27 * @return {XMLHttpRequest}
\r
28 * @throws {Error} If XMLHttpRequest is not supported
\r
31 Util.XHR = function() {
\r
32 // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
\r
33 var XMLHttpFactories = [
\r
34 function () {return new XMLHttpRequest()},
\r
35 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
\r
36 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
\r
37 function () {return new ActiveXObject("Microsoft.XMLHTTP")}
\r
39 /** @type {?XMLHttpRequest} */
\r
41 for (var i=0;i<XMLHttpFactories.length;i++) {
\r
42 try { xhr = XMLHttpFactories[i](); }
\r
43 catch (e) { continue; }
\r
47 throw Error("XMLHttpRequest is not supported");
\r
52 * Fetches a resource.
\r
53 * @param {string} path Resource path
\r
54 * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
\r
55 * be fetched synchronously. If the request failed, contents will be null.
\r
56 * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
\r
59 Util.fetch = function(path, callback) {
\r
60 if (callback && typeof callback != 'function')
\r
63 var fs = require("fs");
\r
65 fs.readFile(path, function(err, data) {
\r
73 return fs.readFileSync(path);
\r
78 var xhr = Util.XHR();
\r
79 xhr.open('GET', path, callback ? true : false);
\r
80 // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
\r
81 xhr.setRequestHeader('Accept', 'text/plain');
\r
82 if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
\r
84 xhr.onreadystatechange = function() {
\r
85 if (xhr.readyState != 4) return;
\r
86 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
\r
87 callback(xhr.responseText);
\r
91 if (xhr.readyState == 4)
\r
96 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
\r
97 return xhr.responseText;
\r
104 * Converts a string to camel case.
\r
105 * @param {string} str
\r
106 * @returns {string}
\r
109 Util.toCamelCase = function(str) {
\r
110 return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
\r
111 return $1.toUpperCase();
\r