How to use new Native Node Watch mode in Node 19

Updated onbyAlan Morel
How to use new Native Node Watch mode in Node 19

Node is constantly improving and adding new features with each major version.

In Node 19, an exciting new feature was added, native watch mode.

In this past, Node developers have had to use third-party libraries to watch for file changes, most notably nodemon. Now, Node has a built-in way to watch for file changes.

In this post, we'll learn how to use the new native watch mode in Node 19.

How to use native Watch mode

Thankfully, the Node team made this feature very easy to use.

To start, let's create a file called main.js and add the following code:

JAVASCRIPT
console.log("Hello from Sabe.io!");

Now normally, you'd run this file with the following command:

BASH
node main.js

And you'd see the following output:

BASH
Hello from Sabe.io!

However, if you want to use the new native watch mode, you'd run the following command:

BASH
node --watch main.js

When you do this, the will get this output:

BASH
Hello from Sabe.io! Completed running 'main.js'

Node lets you know when the file has completed running. This is useful if you want to run a script that takes a long time to run.

Now, if you make a change to the main.js file, like this:

JAVASCRIPT
console.log("This is a change!");

Then you hit save, Node will detect that the file has changed and will run the file again:

BASH
Restarting 'main.js' This is a change! Completed running 'main.js'

Keep in mind that this feature is still experimental, so it may not work in all cases.

However, it's a great feature to have built into Node because it makes it easier to develop Node applications and might potentially allow us to do away with third-party libraries like nodemon in the future.

Conclusion

In this post, we learned how to use the new native watch mode in Node 19.

Simply run your Node application with the --watch flag so that Node knows to run the file again when it detects a change.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.