6 var inherits = require('util').inherits;
7 var delimiter = require('path').delimiter || ':';
8 var ArrayIndex = require('array-index');
14 module.exports = PathArray;
17 * `PathArray` constructor. Treat your `$PATH` like a mutable JavaScript Array!
19 * @param {Env} env - `process.env` object to use.
20 * @param {String} [property] - optional property name to use (`PATH` by default).
24 function PathArray (env, property) {
25 if (!(this instanceof PathArray)) return new PathArray(env);
26 ArrayIndex.call(this);
28 this.property = property || 'PATH';
30 // overwrite only the `get` operator of the ".length" property
31 Object.defineProperty(this, 'length', {
35 // store the `process.env` object as a non-enumerable `_env`
36 Object.defineProperty(this, '_env', {
37 value: env || process.env,
43 // need to invoke the `length` getter to ensure that the
44 // indexed getters/setters are set up at this point
48 // inherit from ArrayIndex
49 inherits(PathArray, ArrayIndex);
52 * Returns the current $PATH representation as an Array.
57 PathArray.prototype._array = function () {
58 var path = this._env[this.property];
60 return path.split(delimiter);
64 * Sets the `env` object's `PATH` string to the values in the passed in Array
70 PathArray.prototype._setArray = function (arr) {
72 this._env[this.property] = arr.join(delimiter);
76 * `.length` getter operation implementation.
81 PathArray.prototype._getLength = function () {
82 var length = this._array().length;
84 // invoke the ArrayIndex internal `set` operator to ensure that
85 // there's getters/setters defined for the determined length so far...
92 * ArrayIndex [0] getter operator implementation.
97 PathArray.prototype[ArrayIndex.get] = function get (index) {
98 return this._array()[index];
102 * ArrayIndex [0]= setter operator implementation.
107 PathArray.prototype[ArrayIndex.set] = function set (index, value) {
108 var arr = this._array();
115 * `toString()` returns the current $PATH string.
120 PathArray.prototype.toString = function toString () {
121 return this._env[this.property] || '';
124 // proxy the JavaScript Array functions, and mutate the $PATH
125 Object.getOwnPropertyNames(Array.prototype).forEach(function (name) {
126 if ('constructor' == name) return;
127 if ('function' != typeof Array.prototype[name]) return;
128 if (/to(Locale)?String/.test(name)) return;
129 //console.log('proxy %s', name);
131 PathArray.prototype[name] = function () {
132 var arr = this._array();
133 var rtn = arr[name].apply(arr, arguments);