Node gets the modules of all js files under the folder

Create index.js

const fs = require('fs')
const path = require('path')

const folderPath = path.join(__dirname, 'api')

console.log('目录路径:', folderPath)

let moduleObj = {}

fs.readdirSync(folderPath).forEach((file) => {
  const filePath = path.join(folderPath, file)
  console.log('文件路径:', filePath)
  // 仅加载 .js 后缀的文件
  if (path.extname(file) === '.js') {
    const moduleName = path.basename(file, '.js')
    const moduleContent = require(filePath)
    moduleObj[moduleName] = moduleContent
  }
})

console.log('模块内容:', moduleObj)

Create an api folder in the same directory

 

Create aa.js under the api folder

console.log('aa1')

module.exports = {
  myFn1: (val) => {
    console.log(val, 'myFn')
  }
}

  Create bb.js under the api folder

console.log('bb1')

module.exports = {
  myFn2: (val) => {
    console.log(val, 'myFn1')
  }
}

console run index.js

node index.js

output:

 

 

Guess you like

Origin blog.csdn.net/qq_41579327/article/details/131534641