javascript - 在 Node 应用程序中定义路径树

标签 javascript node.js path gulp

我有一个带有 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/

相关文章:

javascript - 如何在 WordPress 中将 CSS3 代码转换为 jQuery

javascript - 这段代码:中javascript中的$符号是什么

javascript - req.body 在 Express 应用程序的后路由中未定义

JAVA 文件编写器 : Get the path of created File using FileWriter

javascript - 如果我的 DIV 中没有 P 标签,则删除 div 上的最小高度

javascript - 从 Javascript 调用 PUT 方法

javascript - 错误 : incorrect header check when running post

javascript - 无法连接到 SQLEXPRESS - Node.js

c++ - 使用 boost::filesystem 将文件路径从 Windows 转换为 Linux,然后再转换回来

c++ - 为 ardor boost "too old"并且不会安装