我有一个带有 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
。
但是,这看起来太麻烦了。必须有更好的方法来实现同样的目标。
有人可以就此提供任何建议吗?
最佳答案
您可以使用 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(', '));
关于javascript - 在 Node 应用程序中定义路径树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430316/