930e65bccb39b84938ca3909711933995e81169a
[platform/upstream/nodejs.git] / src / util.js
1 /**
2  * Inherit the prototype methods from one constructor into another.
3  *
4  * The Function.prototype.inherits from lang.js rewritten as a standalone
5  * function (not on Function.prototype). NOTE: If this file is to be loaded
6  * during bootstrapping this function needs to be revritten using some native
7  * functions as prototype setup using normal JavaScript does not work as
8  * expected during bootstrapping (see mirror.js in r114903).
9  *
10  * @param {function} ctor Constructor function which needs to inherit the
11  *     prototype
12  * @param {function} superCtor Constructor function to inherit prototype from
13  */
14 node.inherits = function (ctor, superCtor) {
15   var tempCtor = function(){};
16   tempCtor.prototype = superCtor.prototype;
17   ctor.super_ = superCtor.prototype;
18   ctor.prototype = new tempCtor();
19   ctor.prototype.constructor = ctor;
20 };
21
22 node.assert = function (x, msg) {
23   if (!(x)) throw new Error(msg || "assertion error");
24 };
25
26 node.cat = function(location, encoding) {
27   var url_re = new RegExp("^http:\/\/");
28   var f = url_re.exec(location) ? node.http.cat : node.fs.cat;
29   return f(location, encoding);
30 };
31
32 node.path = new function () {
33   this.join = function () {
34     var joined = "";
35     for (var i = 0; i < arguments.length; i++) {
36       var part = arguments[i].toString();
37
38       /* Some logic to shorten paths */
39       if (part === ".") continue;
40       while (/^\.\//.exec(part)) part = part.replace(/^\.\//, "");
41
42       if (i === 0) {
43         part = part.replace(/\/*$/, "/");
44       } else if (i === arguments.length - 1) {
45         part = part.replace(/^\/*/, "");
46       } else {
47         part = part.replace(/^\/*/, "").replace(/\/*$/, "/");
48       }
49       joined += part;
50     }
51     return joined;
52   };
53
54   this.dirname = function (path) {
55     if (path.charAt(0) !== "/") path = "./" + path;
56     var parts = path.split("/");
57     return parts.slice(0, parts.length-1).join("/");
58   };
59
60   this.filename = function (path) {
61     if (path.charAt(0) !== "/") path = "./" + path;
62     var parts = path.split("/");
63     return parts[parts.length-1];
64   };
65 };
66
67
68 puts = function () {
69   throw new Error("puts() has moved. Use include('/utils.js') to bring it back.");
70 }
71
72 print = function () {
73   throw new Error("print() has moved. Use include('/utils.js') to bring it back.");
74 }
75
76 p = function () {
77   throw new Error("p() has moved. Use include('/utils.js') to bring it back.");
78 }
79
80 node.debug = function () {
81   throw new Error("node.debug() has moved. Use include('/utils.js') to bring it back.");
82 }
83
84 node.error = function () {
85   throw new Error("node.error() has moved. Use include('/utils.js') to bring it back.");
86 }