Stay Ahead of the Game: Leverage Chokidar CLI to Maximize Your Coding Efficiency!
Sohail @chakraframer.com
Posted on November 13, 2024
This article’ll explore a powerful setup that automates managing exports from multiple MongoDB models in your backend code. By leveraging a custom script and Chokidar CLI, you can eliminate the tedious task of manually updating the models/index.ts
file whenever you add or modify your models. Let’s dive in!
Table of Contents
- Introduction
- Prerequisites
- Setting Up the Script
- Implementing Chokidar CLI
- Running the Setup
- Conclusion
Introduction
Managing multiple MongoDB models can become cumbersome, especially when it comes to maintaining the index.ts
file that exports them for better code readability and organization. Manually updating this file every time you add or modify a model can be time-consuming and error-prone.
This article outlines a solution that automates this process, allowing you to focus on writing code instead of managing exports.
Prerequisites
Before we get started, ensure you have the following:
- Node.js installed on your machine
- A working MongoDB instance (optional) as you just export anything
- Basic knowledge of JavaScript and Node.js
Setting Up the Script
- Create a New Script: In your project directory, create a new script file (e.g.,
generateIndex.js
). - Extract Exports from Models: Write a function to read your model files and extract the necessary exports. Here’s a simple example:
import { fileURLToPath } from 'url'
import path, { dirname, join, resolve } from 'path'
import * as fs from 'fs'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const modelsDir = resolve(__dirname, '../models') // Adjust to your `models` folder
const outputFile = join(modelsDir, 'index.ts')
const getModelFiles = (dir: string): string[] => {
let results: string[] = []
const list = fs.readdirSync(dir)
list.forEach((file) => {
const filePath = join(dir, file)
const stat = fs.statSync(filePath)
if (stat && stat.isDirectory()) {
// Recursively get model files from subdirectories
results = results.concat(getModelFiles(filePath))
} else if (file.endsWith('.model.ts') && file !== 'index.ts') {
results.push(filePath)
}
})
return results
}
const files = getModelFiles(modelsDir)
const exports = files.map((file) => {
const relativePath = path.relative(modelsDir, file).replace(/\\/g, '/') // Normalize path for exports
return `export * from './${relativePath.replace('.ts', '')}';`.trim()
})
fs.writeFileSync(outputFile, exports.join('\n'), 'utf8')
-
Save and Test the Script: Run the script to ensure it generates the
src/script/generate-models.ts
file correctly.
src/
├── scripts/
│ └── generateIndex.js
├── models/
│ ├── user.model.ts
│ └── post.model.ts
└── index.ts
Implementing Chokidar CLI
- Install Chokidar CLI: If you haven’t already, install Chokidar CLI globally using npm or save as a dev dependency in your project:
global install
npm install -g chokidar-cli
dev dependency install
npm install --save-dev chokidar-cli
- Set Up File Watching: Use Chokidar to watch your models directory and trigger the script whenever a change is detected:
We will create a few scrips in package.json
file to watch the files and run the script.
"scripts": {
"dev": "tsx watch src/index.ts",
"start": "node dist/index.js",
"compile": "tsc && npm run copy-pug",
"prebuild": "npm run generate-models",
"build": "npm install && npm run compile",
"generate-models": "tsx src/scripts/generate-models.ts",
"watch-files": "chokidar \"src/models/**/*.model.ts\" -c \"npm run generate-model-exports\""
},
Note here we using
tsx
to run the script as we are using TypeScript, but you can replace this withts-node
(Typescript alt) ornode
(JavaScript) to run the script.
- Run the Command: Execute the above command in your terminal to start watching for changes.
npm run watch-files
What Chakridar does is it watches the files and run the script whenever a change is detected.
-
Check the
index.ts
File: Ensure that yourmodels/index.ts
file is correctly updated with the exports from your model files.
export * from './user.model'
export * from './post.model'
Running the Setup
With everything in place, any time you add or modify a model file, Chokidar will automatically run your script, ensuring that your models/index.ts
file is always up to date. This setup will significantly streamline your workflow and enhance productivity.
Conclusion
By implementing this script and using Chokidar CLI, you can automate the management of your MongoDB model exports, allowing you to focus more on development and less on repetitive tasks. Give it a try and see how it boosts your backend code productivity!
But this Chokidar CLI can be used for any file watching and running scripts like compling your Sass, Less or Stylus files, running tests, etc. It's a powerful tool that can save you a lot of time and effort.
Drop some 💖 and 🔥 if you found this article helpful and have any questions or need further clarification, feel free to reach out. Happy coding!
Get In Touch
Posted on November 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 13, 2024