加载某个目录到一个对象上

如果我想加载某个目录到一个对象上,需要如何做呢?

准备

  1. mkdir require-dictory
  2. cd require-dictory
  3. ls
  4. npm init
  5. npm i -S require-directory
  6. touch index.js

核心代码

  1. var requireDirectory = require('require-directory');
  2. module.exports = requireDirectory(module);

测试

touch test.js

  1. var obj = require('./index')
  2. console.log(obj);

然后

  1. require-dictory git:(master) node test.js
  2. { node_modules: { 'require-directory': { index: [Object], package: [Object] } },
  3. package:
  4. { name: 'require-dictory',
  5. version: '1.0.0',
  6. description: '',
  7. main: 'index.js',
  8. scripts: { test: 'echo "Error: no test specified" && exit 1' },
  9. author: '',
  10. license: 'ISC',
  11. dependencies: { 'require-directory': '^2.1.1' } },
  12. test: {} }

此时index对象就返回了index和test和package.json里的内容

测试,创建third.js

  1. require-dictory git:(master) touch third.js
  2. require-dictory git:(master) node test.js
  3. { node_modules: { 'require-directory': { index: [Object], package: [Object] } },
  4. package:
  5. { name: 'require-dictory',
  6. version: '1.0.0',
  7. description: '',
  8. main: 'index.js',
  9. scripts: { test: 'echo "Error: no test specified" && exit 1' },
  10. author: '',
  11. license: 'ISC',
  12. dependencies: { 'require-directory': '^2.1.1' } },
  13. test: {},
  14. third: {} }

此时,这个模块就写完啦,打印出当前模块下的挂载的所有对象