node.js - 用于查找具有多个可能根的文件路径的 Node 模块

标签 node.js

是否有一个 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.jsnode_modules/my-file.js 存在,您将得到 结果 [真,假,真]

关于node.js - 用于查找具有多个可能根的文件路径的 Node 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643212/

相关文章:

node.js - 对记录的更新不会持久保存在 mongodb 数据库中(node js + mongo)

node.js - 使用 Bookshelf 补丁为未引用的列设置默认值

node.js - 来自 mongoDB 的空 [] 响应是 Node.js express get 函数的结果?

node.js - Winston-记录堆栈错误

javascript - Node.js mysql 连接和事务

node.js - 用于 Gulp 配置的 Vinyl FTP

node.js - 如何在 NodeJS 中通过 FTP 下载文件?

node.js - 全局安装 Prettier 但找不到命令

javascript - Meteor js .allow 列表未显示

node.js - 使用 Async/Await 的 Nodemailer 电子邮件确认