是否有一个 Node 模块允许您指定多个根,给它一个文件,然后它尝试查找该文件?
我知道很多库/模块都会做这种事情,但我的 Google-fu 未能找到它的现有模块,这有点令人惊讶。
澄清一下,基本上如果我有这样的配置:
roots: ['node_modules', 'bower_components', 'src']
我要求它查找“my-file.js”,它会搜索以下内容:
node_modules/my-file.js
bower_components/my-file.js
src/my-file.js
并返回第一个解析为现有文件的文件,或者返回错误,指出无法解析该文件。
最佳答案
我也不知道有什么库可以做到这一点,但是您所要求的可以通过几行代码完成:
const fs = require('fs');
const path = require('path');
const roots = ['node_modules', 'bower_components', 'src'];
const myFile = 'my-file.js';
const result = roots.map(root => path.resolve(path.join(root,myFile))).map(fs.existsSync);
这将为您提供与 roots
中每个元素相对应的真/假值数组。因此,如果 src/my-file.js
和 node_modules/my-file.js
存在,您将得到 结果
[真,假,真]
关于node.js - 用于查找具有多个可能根的文件路径的 Node 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643212/