The Wayback Machine - https://web.archive.org/web/20240706124105/https://www.geeksforgeeks.org/node-js-fs-watch-method/
Open In App

Node.js fs.watch() Method

Last Updated : 29 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The fs.watch() method is an inbuilt application programming interface of fs module which is used to continuously watch for changes in the given file or directory. It returns a fs.FSWatcher object that can be used to track the changes in the file.

It has an optional listener as the third argument that can be used to get the changes that take place. This listener has two arguments, one is the name of the file or directory that is modified and the other is the type of modification. While watching a file, if it disappears and reappears, the ‘rename’ event is emitted, and if the file contents are modified the ‘change’ event is emitted.

Note: This method is unreliable and may show multiple events in the listener for each modification.

Syntax:

fs.watch( filename[, options][, listener] )

Parameters: This method accepts three parameters as mentioned above and described below:

  • filename: It is a string, Buffer, or URL that denotes the name of the file or directory to be watched.
  • options: It is a string or object that can be used to modify the behavior of the method. It is an optional parameter. It has the following parameters: 
    • persistent: It is a Boolean value that is used to specify if the process should continue as long as the files are being watched. The default value is true.
    • recursive: It is a Boolean value that is used to specify if all the subdirectories of the given directory should be watched. The default value is false.
    • encoding: It is a string that specifies the character encoding that has been used for the filename passed to the listener.
  • listener: It is a function that is invoked when the file is accessed or modified. It is an optional parameter.
    • eventType: It is a string that specifies the type of modification that the file underwent.
    • filename: It is a string or Buffer that specifies the filename on which the event is triggered.

Return Value: It returns a fs.StatWatcher object when the function is successfully called. 

Below examples illustrate the fs.watch() method in Node.js:

Example 1: This example shows the usage of the watch() method on a file.

javascript




// Node.js program to demonstrate the
// fs.watch() method
  
// Import the filesystem module
const fs = require('fs');
  
fs.watch("example_file.txt", (eventType, filename) => {
  console.log("\nThe file", filename, "was modified!");
  console.log("The type of change was:", eventType);
});
  
// Renaming the file to a new name
setTimeout(
  () => fs.renameSync("example_file.txt", "new_file.txt"),
  1000
);
  
// Renaming the file back to its old name
setTimeout(
  () => fs.renameSync("new_file.txt", "example_file.txt"),
  2000
);
  
// Changing the contents of the file 
setTimeout(
  () => fs.writeFileSync("example_file.txt", 
  "The file is modified"), 3000
);


Output: Note that this method is unreliable and may show multiple events for every modification.

The file example_file.txt was modified!
The type of change was: rename

The file example_file.txt was modified!
The type of change was: rename

The file example_file.txt was modified!
The type of change was: change

Example 2: This example shows the usage of the watch() method on a directory.

javascript




// Node.js program to demonstrate the
// fs.watch() method
  
// Import the filesystem module
const fs = require('fs');
  
fs.watch("ex_dir", (eventType, filename) => {
  console.log("\nThe file", filename, "was modified!");
  console.log("The type of change was:", eventType);
});
  
// Changing the contents of a file 
setTimeout(
  () => fs.writeFileSync("ex_dir/ex1.txt", 
  "The file is modified"), 1000
);
  
// Renaming a file to a new name
setTimeout(
  () => fs.renameSync("ex_dir/ex2.txt", 
  "ex_dir/new_ex2.txt"), 2000
);


Output: Note that this method is unreliable and may show multiple events for every modification.

The file ex1.txt was modified!
The type of change was: change

The file ex2.txt was modified!
The type of change was: rename

The file new_ex2.txt was modified!
The type of change was: rename

Reference: https://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener



Previous Article
Next Article

Similar Reads

What is the difference between $watch and $observe in AngularJS ?
AngularJS provides different methods to observe/watch the changes in its elements and variables. The $observe and $watch are two different methods that serve this purpose. $observe is a method that is responsible to observe/watch the changes in the DOM attribute. We use $observe when we want to observe a DOM element that contains interpolation ({{}
3 min read
How to watch service variables ?
$scope acts as a built-in object in AngularJs. It consists of application data and methods. The $scope is acts as a link between a controller and view (HTML). $scope is used to transfer the data. $watch: Scope in AngularJs object has $watch event which comes into picture when the model property gets changed or altered. When a data binding is create
4 min read
Create a Stop Watch using ReactJS
We can create Stop Watch in ReactJS using the following approach. Our StopWatch will have the functionality of Start, Pause, Resume and Reset. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app stopwatch Step 2: After creating your project folder i.e. stopwatch, mov
4 min read
SASS --watch with automatic minify
SASS is the abbreviation of Syntactically Awesome Style Sheets. It is a CSS pre-processor with syntax advancements. The stylesheets in this syntax are processed by a program and compiled into regular CSS style sheets, which can be used in the website. You can read more about SCSS by clicking here. In this tutorial, we will discuss the various metho
3 min read
How to Create a Stop Watch using Next.js ?
In this article, we will create a Stop Watch Using Next.js. Our StopWatch will have the functionality of Start, Pause, Resume, and Reset. Next.js is based on React, Webpack, and Babel. It is an awesome tool for creating web applications and is famous for server-side rendering. Next.js is built by Zeit. Developers with knowledge of HTML, CSS, JavaSc
3 min read
Create a Stop Watch using React Native
React Native simplifies cross-platform app development for iOS, Android, and the web using a single codebase. Install Node.js, Expo CLI, and leverage Expo's seamless experience for creating high-performance apps. Stopwatches servetime as vital tools for accurately measuring time­ intervals. By the capabilitieswe of React Native, we can effortle­ssl
4 min read
How to Properly Watch for Nested Data in VueJS ?
In Vue.js, we can watch the nested data to properly control the changes within the nested properties. In this article, we will explore both of the approaches with the practical implementation of these approaches in terms of examples and outputs. We can watch this by using two different approaches: Table of Content Using deep: true OptionUsing Compu
3 min read
How to Watch Store Values from Vuex ?
VueJS is one of the best frameworks for JavaScript like ReactJS. The VueJS is used to design the user interface layer. It is compatible with other libraries and extensions as well. In this article, we will learn How to watch store values from Vuex. Table of Content Using Vue optionsUsing ComponentsApproach 1: Using Vue optionsIn this approach, we'r
3 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
three90RightbarBannerImg