当前位置: 首页 > 后端技术 > Node.js

我写了一个叫requireDir的小工具,可以遍历一个目录,require目录下所有js文件的代码在这里使用

时间:2023-04-04 00:29:19 Node.js

:因为还没有发布到npm,所以复制这个文件里的代码build自己一个模块。例如调用require-dir.jsconstrequireDir=require('path/to/require-dir')第一个参数固定为__dirname,第二个参数为需要require的目录。多次加载同一个目录时,第一次加载的结果会被缓存,当你再次使用requireDirrequire目录时,会直接获取缓存的对象,而不是再次使用fs读取目录。假设目录结构如下:|_src||_啦啦啦||_wx目录|||_event.js|||_other-thing.js|对象,对象的属性结构与目录结构一致。如果文件夹或文件名中有非字母数字字符,该字符将从相应的对象属性中删除,并以驼峰命名并以其作为分隔符,如下所示other-thing.jsconstlalala=requireDir(__dirname,'path/to/lalala')lalala的结构是,{user:require('path/to/user.js')wxdir:{event:require('path/to/event.js'),otherThing:require('path/to/other-thing.js')}}2.并行结构1.仍然迭代整个目录的js,但是返回的对象不是树结构,而是相对于传入的路径constlalala2=require(__dirname,'path/to/lalala',true)lalala2的结构是{user:require('path/to/user.js'),wxdirEvent:require('path/to/event.js'),wxdirOtherThing:require('path/to/other-thing.js')}2.自定义命名规则,第三个参数可以传入一个对象{nameHandler:func},func的唯一参数是一个字符串,返回值仍然是一个字符串,requireDir返回的对象的属性是传入funcconstlalala3=require(__dirname,'path/to/lalala',{nameHandler:i=>`$${i}`})lalala3的结构是{$user:require('path/to/user.js'),$wxdirEvent:require('path/to/event.js'),$wxdirOtherThing:require('path/to/other-thing.js')}