Nodemon in Node Js

  • Nodemon is a utility for Node.js that helps in automatically restarting the server whenever changes are detected in the source code. It is particularly useful during the development phase, as it eliminates the need to manually stop and restart the server every time you make changes to your code.
Here's a detailed explanation of Nodemon with an example:
  • Installation: You can install Nodemon globally using npm:


    npm install -g nodemon

  • Usage: Instead of running your Node.js application directly with the `node` command, you can use `nodemon` to run it:


    nodemon your-app.js

  • Example: Let's consider a simple Node.js server file named `app.js`:

    // app.js
    const http = require('http');

    const server = http.createServer((req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Hello, Nodemon!\n');
    });

    const PORT = 3000;
    server.listen(PORT, () => {
        console.log(`Server running at http://localhost:${PORT}/`);
    });

  • If you run the server using the `node` command, you would do:

    node app.js

  • However, if you want to use Nodemon, you run:

    nodemon app.js

  • The `nodemon.json` file allows you to define configuration options for `nodemon` in a dedicated configuration file, providing a cleaner and more organized way to manage settings. Here are some commonly used configurations that you can include in your `nodemon.json` file:
  • Watched Directories and Files: Use the `watch` property to specify which directories or files `nodemon` should monitor for changes.

    {
        "watch": [
            "src",
            "config"
        ]
    }

  • Ignored Files: The `ignore` property allows you to specify files or patterns that should be ignored by `nodemon`. This is useful for excluding files or directories that shouldn't trigger a restart.

    {
        "ignore": [
            "logs",
            "public"
        ]
    }

  • File Extensions to Watch: You can use the `ext` property to define the file extensions that `nodemon` should watch for changes. This is useful if your project includes files with extensions other than `.js`.

    {
        "ext": "js,json"
    }

  • Executing Commands Before Restart: The `events` property allows you to specify commands to be executed before the application restarts. This can include tasks like linting or running tests.

    {
        "events": {
            "restart": "npm test"
        }
    }

  • Delaying Restart: You can add a delay before `nodemon` restarts the application using the `delay` property. This can be helpful to allow time for build tasks to complete.

    {
        "delay": "1000"
    }

  • Environment Variables: Define environment variables using the `env` property. This is useful for providing specific configuration options based on different environments.

    {
        "env": {
            "NODE_ENV": "development",
            "PORT": 3000
        }
    }

  • Recursive Watch: Use the `recursive` property to enable recursive file watching. This can be helpful if your project has a nested directory structure.

    {
        "recursive": true
    }

  • Custom Script: The `exec` property allows you to specify a custom script to run instead of the default application script. This can be useful if you have a more complex setup.

    {
        "exec": "babel-node server.js"
    }

  • Here's an example of a more comprehensive `nodemon.json` file:

    {
        "watch": [
            "src",
            "config"
        ],
        "ignore": [
            "logs",
            "public"
        ],
        "ext": "js,json",
        "events": {
            "restart": "npm test"
        },
        "delay": "1000",
        "env": {
            "NODE_ENV": "development",
            "PORT": 3000
        },
        "recursive": true,
        "exec": "babel-node server.js"
    }

  • Adjust these configurations based on your project's needs, and feel free to explore additional options in the official `nodemon` documentation for more advanced use cases: nodemon documentation (https://github.com/remy/nodemon#config-files).
  • Events and Logging: Nodemon provides a variety of events and logging options, allowing you to customize the output and behavior.

    nodemon --verbose


Signal Property:
  • In `nodemon`, the `signal` property in the `nodemon.json` configuration file is used to specify the signal that `nodemon` should send to the running process when it needs to restart or shut down the application. This property is particularly useful when integrating `nodemon` with processes that handle signals differently.
Here's how you might use the `signal` property in your `nodemon.json`:


    {
        "signal": "SIGUSR2"
    }

  • In this example, the `signal` property is set to `"SIGUSR2"`. This means that when `nodemon` decides to restart the application, it will send the `SIGUSR2` signal to the running process. The running process, in turn, can handle this signal in a specific way, such as gracefully shutting down connections before restarting.
Common signals used with `nodemon` include:
  • SIGUSR2: This signal is often used for graceful shutdowns and restarts. Many applications, especially those using process managers like PM2, listen for this signal to perform cleanup operations before restarting.
  • SIGINT (Ctrl+C): This signal is the default when you press Ctrl+C to manually stop `nodemon`. It typically triggers an immediate shutdown.
  • SIGTERM: Another signal used for termination. It's similar to SIGINT but may be handled differently by some processes.
  • SIGKILL: A forceful termination signal. It immediately terminates the process without giving it a chance to clean up.
Here's an example of how you might use the `signal` property in the context of a `nodemon.json` file:


    {
        "watch": [
            "src"
        ],
        "signal": "SIGUSR2",
        "env": {
            "NODE_ENV": "development"
        }
    }

  • In this example, when changes are detected in the `src` directory, `nodemon` will send the `SIGUSR2` signal to the running process, triggering a restart. Adjust the signal based on the requirements of your application and how it handles graceful restarts or shutdowns.
  • These features make Nodemon a valuable tool for Node.js developers, making the development process more efficient by automatically restarting the server upon code changes. It is important to note that Nodemon is typically used during development and should not be used in production environments.

No comments:

Post a Comment