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 š