How to use new Native Node Watch mode in Node 19
Table of Contents
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:
JAVASCRIPTconsole.log("Hello from Sabe.io!");
Now normally, you'd run this file with the following command:
BASHnode main.js
And you'd see the following output:
BASHHello from Sabe.io!
However, if you want to use the new native watch mode, you'd run the following command:
BASHnode --watch main.js
When you do this, the will get this output:
BASHHello 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:
JAVASCRIPTconsole.log("This is a change!");
Then you hit save, Node will detect that the file has changed and will run the file again:
BASHRestarting '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!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript