nodemon, node.js, express

Table of Contents

Introduction

When developing with Node.js and Express, managing application restarts can quickly become a hassle. That’s where nodemon comes in. This powerful tool automatically restarts your server whenever changes are made to your project files, saving you time and improving your development workflow. By using nodemon with Node.js and Express, you can focus more on writing code and less on manual restarts. In this article, we’ll walk you through how to install and configure nodemon for your Node.js applications, including how to integrate it seamlessly with an Express project.

What is Nodemon?

Nodemon is a tool that automatically restarts a Node.js application whenever changes are made to the code. This eliminates the need for manual restarts during development, saving time and improving workflow efficiency.

Step 1 — Installing Nodemon

Alright, first things first, you’ll need to install nodemon on your machine. Nodemon is a super handy tool that will automatically restart your Node.js app every time a file changes, saving you from manually restarting the server each time you tweak your code. Pretty neat, right?

You can install nodemon in two ways: globally or locally. Whether you choose to install it globally or locally depends on your needs. If you want to use it across all your projects, you should go for a global installation. But if you just want it for a specific project, then the local installation is the way to go.

Global Installation

If you want to install it globally so that it’s available in any project, you can do so with npm by running this command:

$ npm install nodemon –global

Or if you prefer yarn as your package manager, you can run:

$ yarn global add nodemon

Once installed globally, you can use nodemon from anywhere on your system, which is pretty convenient when jumping between different projects.

Local Installation

Now, let’s say you only want to use nodemon in one project. In that case, you can install it locally, which keeps it confined to a single project. To install nodemon locally with npm, run:

$ npm install nodemon –save-dev

Alternatively, if you’re using yarn, the command would be:

$ yarn add nodemon –dev

This is ideal for keeping your project environments isolated and not affecting any other projects you might have on your machine.

What’s the Catch with Local Installation?

One thing to keep in mind with local installations is that you won’t be able to run the nodemon command directly from the terminal. Instead, you’ll need to reference it from the node_modules/.bin directory inside your project. If you try running nodemon directly, you might run into an error like:

Output
command not found: nodemon

But don’t worry, it’s an easy fix! Instead of running just nodemon, you can specify the full path like this:

$ ./node_modules/.bin/nodemon.js [your node app]

This will allow you to run nodemon from the local installation. And the best part is, you can also use it inside npm scripts or even with npx if that’s more your style. This flexibility helps keep things tidy, while still giving you the awesome power of automatic restarts with nodemon.

So whether you go global or local, nodemon is here to make your development process smoother and save you time by handling those restarts for you. Enjoy coding without the manual restart hassle!

For more information on automating development tasks with tools like nodemon, check out this comprehensive guide on Nodemon package documentation.

Step 2 — Setting Up an Example Express Project with Nodemon

Once you’ve installed nodemon, it’s time to bring your project to life. Let’s start by setting up a simple Express server. Now, if you haven’t heard of Express before, it’s a minimal and flexible Node.js web application framework that’s perfect for building web apps and APIs quickly. Imagine this: you’re working on an app, and you’ve got a server.js file that holds the core logic of your server. With nodemon by your side, you won’t have to manually restart your server each time you tweak the code. Nodemon will automatically restart the server the moment it detects any changes. So, let’s get started!

First, you’ll need to create a new project directory. Once you’re in your terminal, navigate to that directory and initialize a new Node.js project by running this command:

$ npm init -y

This creates a package.json file, which helps manage all your project’s dependencies. Now that that’s set up, you’ll need to install Express by running:

$ npm install express

Once the installation is done, create a server.js file inside your project folder. This file is going to be the entry point for your Express server. Here’s a basic example of what your server.js file might look like:


const express = require(‘express’);
const app = express();
const port = 3000;app.get(‘/’, (req, res) => {
    res.send(‘Dolphin app listening on port ‘ + port + ‘!’);
});app.listen(port, () => {
    console.log(`Dolphin app listening on port ${port}!`);
});

This simple code sets up an Express server that listens on port 3000. When you visit the root URL (/), the server responds with “Dolphin app listening on port 3000!”.

Now that your server is ready, let’s bring in the magic of nodemon. To run your server with nodemon, all you need to do is type this command in your terminal:

$ nodemon server.js

And here’s where nodemon shows off. When you run this command, nodemon starts your Express server and automatically watches for changes in your project files. This means that as soon as you make any changes to the server.js file, nodemon will detect those changes and restart the server.

For example, let’s say you update the server.js file to change the message that the server displays, like this:


app.get(‘/’, (req, res) => {
    res.send(‘Shark app listening on port ‘ + port + ‘!’);
});

After saving the file, nodemon will notice the change, restart the server, and you’ll see the new message pop up: “Shark app listening on port 3000!”. The beauty of this is that you don’t have to manually stop and restart the server. Nodemon handles it all for you.

This automatic restart is a game-changer during development. It saves time and removes the need to worry about restarting your server every time you update your code.

And if you want to take it even further, nodemon lets you pass in arguments. For example, you can specify a different port number in the command like this:

$ nodemon server.js 3006

Now, your server will listen on port 3006 instead of the default port 3000. Nodemon makes implementing these changes super easy, allowing you to focus on coding rather than managing server restarts.

And just like that, you’ve got an Express server running with nodemon watching over your files. Now you can make tweaks to your app and see the changes live, without any interruptions. Enjoy the seamless development process!

For further guidance on building and deploying Express applications, refer to this helpful Express Installation Guide.

Step 3 — Nodemon Options

Once you’ve set up nodemon and have your Node.js application running smoothly, you may realize that you want more control over how nodemon behaves. This is where the real magic of nodemon comes in with its various configuration options. By using these options, you can customize how nodemon monitors your project, what it restarts, and even the way your application runs. Let’s dive into some of the most useful options that nodemon offers.

–exec

The --exec option lets you specify a different binary to run when a file change is detected. This is especially handy if you need to run a specific tool or script instead of the default node command.

For example, let’s say you’re working with TypeScript and you want to use ts-node to run your TypeScript files. Instead of typing ts-node every time you want to run your app, you can simply tell nodemon to use it automatically with this command:

$ nodemon –exec ts-node server.ts

Now, every time there’s a change in your project, nodemon will run ts-node to execute server.ts , keeping you in your development flow without needing to type extra commands.

–ext

The --ext option is a life-saver when you want to specify the exact types of files nodemon should watch. By default, nodemon looks for changes in .js, .mjs, .json, .coffee, and .litcoffee files. But what if you’re working with TypeScript and want to track .ts files as well? With the --ext option, you can easily include those file types:

$ nodemon –ext js,ts server.js

Now, nodemon will monitor both .js and .ts files for changes. You get the flexibility to include the file types that are important to your project.

–delay

Sometimes, you might want to delay the restart process after a file change. By default, nodemon waits for one second before restarting, but you can customize this to your needs using the --delay option.

For example, if your application is slow to start, or if you want to avoid rapid restarts while you’re making multiple changes, you can set a longer delay:

$ nodemon –delay 3.5 server.js

This tells nodemon to wait 3.5 seconds after detecting a file change before restarting the process. It’s perfect for avoiding those unnecessary restarts during fast editing.

–watch

The --watch option allows you to tell nodemon exactly which files or directories to focus on. By default, it watches the current directory and all subdirectories. But if you want to optimize things and only watch specific files or folders, you can use --watch .

Let’s say all your code lives in a folder called src, and you only want to monitor that folder. You can do this:

$ nodemon –watch src server.js

If you have multiple directories you want to watch, you can specify them with additional --watch flags:

$ nodemon –watch src –watch config server.js

Now, nodemon will watch both the src and config directories for changes.

–ignore

At times, you might not want certain files or directories to trigger a restart when they’re modified. This is where the --ignore option comes in handy. For example, you might have test files or log files that don’t require the server to restart when updated.

If you want to ignore .test.js files, for instance, you can add this to your command:

$ nodemon –ignore *.test.js server.js

This ensures that nodemon won’t restart when .test.js files are modified.

–verbose

If you ever find yourself needing more detailed information about what’s happening under the hood, the --verbose option is exactly what you need. It gives you more detailed output in the terminal, letting you see exactly which files were modified to trigger the restart. To enable verbose mode, just add --verbose to your command:

$ nodemon –verbose server.js

This is especially useful when you’re troubleshooting an issue with your nodemon setup or just want to keep track of exactly what’s happening.

Combining Options

The cool thing about nodemon is that you can mix and match all these options to create a development environment that suits you perfectly. For example, if you’re working with TypeScript, want to watch both .js and .ts files, and prefer a 3-second delay before the server restarts, you can use this command:

$ nodemon –exec ts-node –ext js,ts –delay 3 server.ts

This command sets everything up for a seamless TypeScript development experience, while nodemon handles all the behind-the-scenes work. You can combine these options any way you like, giving you total control over your development workflow.

With all these nodemon options at your disposal, you can fine-tune your development setup to fit your exact needs. Whether it’s choosing specific files to watch, controlling how and when your server restarts, or ignoring certain files altogether, nodemon gives you the tools to keep things running smoothly and efficiently.

For more information on optimizing your development environment with various command-line options, check out this detailed Nodemon Options Guide.

Step 4 — Nodemon Configurations

At some point, you might find yourself running into the problem of repeatedly adding the same options when you start your server. That’s where configuration files like nodemon.json or the package.json file come in. These configuration files save you time by letting you set up your settings once, and then nodemon automatically picks them up each time you run it.

One major benefit of using a configuration file is that it makes sharing your setup with others super easy. Everyone working on the project will have the same nodemon settings, which keeps things consistent. Let’s explore how you can set up your own nodemon configuration to make your development process a bit more seamless and efficient.

Using nodemon.json

The first option is creating a nodemon.json file in your project’s root directory. This is a nice, clean way to keep your settings separate from your other project files, and it makes it easy to update those settings without having to tweak the command line every time you start nodemon.

For example, let’s say you want nodemon to watch specific directories, use TypeScript, and add a little delay before restarting. You can do that by creating a nodemon.json file with the following content:


{
   “watch”: [
     “server”
   ],
   “ext”: “ts”,
   “ignore”: [
     “*.test.ts”
   ],
   “delay”: “3”,
   “execMap”: {
     “ts”: “ts-node”
   }
}

Here’s what each part of this configuration does:

  • watch : This tells nodemon to watch changes in the server directory.
  • ext : This specifies that .ts (TypeScript) files should be monitored.
  • ignore : This ensures that files ending in .test.ts don’t trigger a restart.
  • delay : This adds a 3-second delay before restarting after a change is detected.
  • execMap : This tells nodemon to use ts-node to run TypeScript files.

This setup is super helpful if you often need to tweak how nodemon behaves.

Using package.json for Configuration

If you prefer to keep everything in one place and avoid dealing with multiple configuration files, you can add your nodemon settings directly to your package.json . This is especially handy for smaller projects where you don’t need to manage a separate file for just the nodemon config.

Here’s how you can add the same configuration from the nodemon.json example to your package.json :


{
   “name”: “nodemon-example”,
   “version”: “1.0.0”,
   “description”: “”,
   “nodemonConfig”: {
     “watch”: [
       “server”
     ],
     “ext”: “ts”,
     “ignore”: [
       “*.test.ts”
     ],
     “delay”: “3”,
     “execMap”: {
       “ts”: “ts-node”
     }
   },
   “scripts”: {
     “start”: “nodemon server/server.ts”
   }
}

Here’s a breakdown of the key parts:

  • nodemonConfig : This section is where you define all the same settings as you would in the nodemon.json file.
  • scripts : This section includes a start command, which tells nodemon to start the server with the specified script.

By putting your configuration in the package.json file, you keep everything in one place. This is a great option when managing dependencies or working on projects where you prefer not to have multiple configuration files.

Benefits of Configuration Files

Having a configuration file for nodemon comes with a lot of perks:

  • Consistency: You don’t have to remember to add the same options every time you start the server. The settings are applied automatically.
  • Portability: If you’re working in a team, everyone will have the same configuration without needing to set up their environment manually.
  • Flexibility: You can easily tweak your settings whenever needed—whether it’s adjusting the delay, adding directories to watch, or changing which files get executed.

By using a configuration file, you ensure that your development environment stays the same across all machines and platforms, which means you don’t have to deal with complicated setups each time you start a new project.

Additional Configuration Options

We’ve covered some of the basic configuration options, but nodemon offers a lot more flexibility. If you’re curious about all the available options, you can always check them out by running:


$ nodemon –help

This command will show you a list of all the options you can use, allowing you to fine-tune how nodemon works for your particular needs.

To explore more about how to configure and manage nodemon efficiently, check out this comprehensive guide on Nodemon Configurations.

Conclusion

In conclusion, using nodemon with Node.js and Express is a game-changer for developers looking to streamline their workflow. By automatically restarting your server whenever changes are made, nodemon eliminates the need for manual restarts, saving valuable time and effort during development. Whether you’re installing nodemon globally or locally, its configuration options make it easy to integrate into any Node.js project. As development environments continue to evolve, tools like nodemon will remain essential in speeding up the development process, allowing developers to focus more on coding and less on administrative tasks. With its simple setup and flexibility, nodemon is an indispensable tool for modern web development.Looking ahead, we can expect even more powerful integrations and enhancements to nodemon, further simplifying development processes in Node.js and Express applications.

Docker system prune: how to clean up unused resources (2023)

Any Cloud Solution, Anywhere!

From small business to enterprise, we’ve got you covered!

Caasify
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.