Dynamic import of multiple modules using require.context in node Js

Consider you want to import all the SQL files from a directory and execute them in your node js application. You can do it using require.context in node js.

// require.context to import dynamically all the SQL files from a directory
const sqlFilesContext = require.context('./sql', false, /\.sql$/)

const sqlFiles = sqlFilesContext.keys().forEach((key) => {
  const sqlFilePath = `./sql/${key}`
  console.log(`Importing SQL file: ${sqlFilePath}`)

  // You can add your logic here to execute the SQL file
})

Why not use fs module?

You can also do the same thing using fs module in node js.

// fs module to import dynamically all the SQL files from a directory
const fs = require('fs')
const path = require('path')

const sqlFiles = fs
  .readdirSync(path.resolve(__dirname, './sql'))
  .forEach((sqlFile) => {
    const sqlFilePath = `./sql/${sqlFile}`
    console.log(`Importing SQL file: ${sqlFilePath}`)

    // You can add your logic here to execute the SQL file
  })

But require.context is more convenient and easy to use,

  • It allows you to import multiple modules from a directory dynamically.
  • It allows you to filter the modules to be imported using a regular expression.
  • It allows you to import modules from a directory recursively.

Hope you learned some tricks on Node Js using require.context. Please share with your friends if you find it useful šŸ™Œ

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months