In this lesson, you will learn how to use Node.js command-line flags to preload critical modules before your main application code ever executes.
Why Preload?
Normally, when you run a Node.js application, your modules are loaded and initialized only when require or import statements are encountered in your code. However, there are times—such as initializing performance monitors, setting up custom error handlers, or patching global objects—where you need specific logic to run before your application starts.
Instead of cluttering your entry point with these setup tasks, you can use the --require (or -r) flag. This tells Node.js to load a specific module immediately upon startup, effectively injecting it into your runtime environment.
Practical Usage
Imagine you have a performance monitoring file named telemetry.js that needs to be active from the very first millisecond of your app's life.
If your standard entry point is app.js, you would typically run it like this:
node app.js
To ensure telemetry.js initializes first, you simply prepend the -r flag:
node -r ./telemetry.js app.js
When you run this command, Node.js performs the following steps:
- It looks for
telemetry.js. - It executes the entire contents of that file.
- Only after
telemetry.jshas finished running does it move on toapp.js.
Use Cases
This technique is highly effective for:
- Environment Setup: Loading configuration schemas or validating variables before the rest of the code runs.
- Instrumentation: Attaching telemetry or logging agents that need to wrap your entire application lifecycle.
- Monkey-patching: Applying necessary runtime patches to global objects or built-in modules before your app logic attempts to use them.
By offloading these requirements to the runtime environment, you keep your app.js file clean and focused on business logic, while ensuring that the infrastructure supporting your application is always ready and waiting.
Key Takeaway: Use the -r (or --require) flag to execute critical startup modules before your main application code, ensuring your environment is fully configured and instrumented from the very first line of execution.