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 🙌

Beginners to ProNode Js

Visual Guide to API Design Best Practices

This visual eBook covers essential best practices for designing robust APIs using REST principles.

This book is ideal for beginners and backend developers seeking to enhance their API design skills. However, it is not suited for those seeking an in-depth exploration of API design. This book is a quick read under 40 slides like scrolling through your instagram feed.

Visual Guide to API Design Best Practices