我有一个带有Gulp的Node.js应用程序,它具有最多约5个级别的深层目录结构。
不幸的是,我无法找到更好的方法来定义Gulp构建的路径。所以我开始做以下事情,
var path = require('path'),
_joinPaths = function (parent, subPath) {
return parent.dir ? path.join(parent.dir, subPath) : subPath;
},
_subPath = function (parent, propName, subPath) {
subPath = subPath || propName;
parent[propName] = {
dir: _joinPaths(parent, subPath)
};
},
_entryPath = function (parent, entryPath) {
parent.entry = _joinPaths(parent, entryPath);
},
_pathPattern = function (parent, includes, excludes) {
};
function Paths() {
var paths = {};
_subPath(paths, 'src', './');
_subPath(paths.src, 'lib');
// Define more paths
};
所以最后我可以像paths.src.lib
那样访问路径。
然而,这看起来太麻烦了。必须有更好的方法来实现同样的目标。
有人可以就此提出任何建议吗?
答案 0 :(得分:1)
您可以使用ES2015功能
<强>代理强>:
const proxyPath = require('../');
var tmp = proxyPath('/tmp');
console.log(tmp.cache['project-1']['..'].files + ''); // /tmp/cache/files
代理代码:
const path = require('path');
const fs = require('fs');
module.exports = structure;
const cache = new Map();
function structure(root) {
var dir = path.resolve(root);
var dirs;
if (! cache.has(dir)) {
if (fs.existsSync(dir)) {
dirs = fs.readdirSync(dir + '');
} else {
dirs = [];
}
cache.set(dir, dirs);
} else {
dirs = cache.get(dir);
}
function toString() {
return dir;
}
return new Proxy({}, {
has(target, prop) {
return dirs.indexOf(prop) > -1;
},
ownKeys(target) {
return [...dirs];
},
get(target, prop) {
switch (prop) {
case Symbol.toPrimitive:
case 'toString':
case 'valueOf':
return toString;
break;
default:
if (typeof prop === 'string') {
return structure(path.resolve(dir, prop));
} else {
return dir[prop];
}
}
}
});
}
类继承自数组as npm module:
const fs = require('fs');
const path = require('path');
const DIR = Symbol('DirectoryArray.Dir');
class DirectoryArray extends Array {
// Load directory structure if it exists
constructor(dir) {
super();
this[DIR] = path.resolve(dir);
if (fs.existsSync(this[DIR])) {
this.push(...fs.readdirSync(this[DIR]));
}
}
// Create Directory array from relative path
// supports '..' for lookup
dir(dir) {
return new this.constructor(
path.resolve(
this[DIR], dir
)
);
}
toString() {
return this[DIR];
}
}
DirectoryArray.Dir = DIR;
// Usage example
var cwd = new DirectoryArray(process.cwd());
var test = cwd.dir('test');
console.log(cwd + '');
console.log(cwd.join(', '));
console.log(test + '');
console.log(test.join(', '));