ノードはフォルダー内のすべての js ファイルのモジュールを取得します

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)

同じディレクトリに API フォルダーを作成します

 

aa.jsをapiフォルダ配下に作成します。

console.log('aa1')

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

  apiフォルダーの下にbb.jsを作成します。

console.log('bb1')

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

コンソールでindex.jsを実行

node index.js

出力:

 

 

おすすめ

転載: blog.csdn.net/qq_41579327/article/details/131534641