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
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Setting Up Stylus CSS Preprocessor