Node.JS FS.Watch Example

Node js fs.watch method is used to monitor a file change event such as write data to file, delete data from a file. This example will show you how to use it to implement a data server that can monitor server-side file data change and send changed data back to the client browser.

1. Node JS FS Watch Example Overview.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/HPgQ4uxknnc

  1. This example will demonstrate the below functions.
  2. Create an HTTP server which will listen for client request and store server response object to a global variable.
  3. The global variable will be used to send changed file data back to the client browser.
  4. Create a backend function that will write data to a file regularly.
  5. Monitor data file change event when data is added to the text file and send the changed data back to the client.

2. Node JS FS Watch Example Source Coe.

  1. To use the Node JS fs module watch function, you should first import the fs module then run the below code.
    var fileSystem = require("fs");
    
    // This is the fs watch function.
    fileSystem.watch(messageFile, function(event, filename) {
       ......
    });
  2. This example core files are httpServer.js, readData.html. The message text file is message.txt.
    C:\WORKSPACE\WORK\DEV2QA.COM-EXAMPLE-CODE\JAVASCRIPTEXAMPLEWORKSPACE\NODEJSWORKSPACE\NODEJSLISTENFILECHANGE
    │   httpServer.js
    │   message.txt
    │   readData.html
  3. httpServer.js
    // Import fs, http module.
    var fileSystem = require("fs");
    var http = require('http');
    
    // Client user is used to send data back to client browser.
    var clientUser = null;
    
    // The current read position in the text file.
    var currReadPos = 0;
    
    // The message file name.
    var messageFile = "message.txt";
    
    // Save one line of text of the file.
    var lineText = '';
    
    // Create http server and listen on port 8888.
    http.createServer(function(request, response) {
    
        response.writeHead(200, {
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
        });
    
        // Assign response object to clientUser then clientUser can send data through http back to client.
        clientUser = response;
    
        response.write('Server returned data will be listed below. \n');
    
        // When client browser close the connection.
        response.socket.on('close', function() {
    
            clientUser = null;
    
        });
    }).listen(8888);
    
    console.log("Http server started, you can access http://localhost:8888/readData.html to access this example.")
    
    // This function will send one line text in the message file back to client.
    var sendMessageToClient = function(fd) {
    
        var buffer = new Buffer(1);  
    
        fileSystem.read(fd, buffer, 0, 1, currReadPos, function(err, num) {
    
            if(!err && num > 0 && clientUser) {
    
                // Current read position plus 1.
                currReadPos = currReadPos + 1;
    
                var charactor = buffer.toString();
    
                // If the charactor is a return charactor.
                if(charactor=="\n")
                {
                    // Send the text line back to client.
                    clientUser.write(lineText + '\n\n');
    
                    lineText = '';
                }else
                {
                    lineText += charactor;
                }
    
                // Run sendMessageToClient function after while.
                return process.nextTick(function() {
    
                    sendMessageToClient(fd);
    
                });
            }
        });
    };
    
    
    // This function is used to monitor the message text file data change.
    function watchFileDataChange() {
    
        fileSystem.open(messageFile, 'r', function(err, fd) {
    
            if(err) {
                return setTimeout(watchFileDataChange, 3000);
            }
    
            // This is the fs watch function.
            fileSystem.watch(messageFile, function(event, filename) {
    
                // If data change then send new text back to client.
                if(event === "change") {
    
                    sendMessageToClient(fd);
    
                }
            });
        });
    };
    
    // Run watch file data change function.
    watchFileDataChange();
    
    
    // This function will write data to message.txt every 3 seconds.
    function writeDataToMessageFile(){
    
        // Create the write stream.
        var writeStream = fileSystem.createWriteStream(messageFile, {
            flags : "a"
        });
    
        var timeOutFunction = function () {
            var date = new Date();
            writeStream.write(date.getMilliseconds() + ' - hello, this is a node implement data server from dev2qa.com ');
            writeStream.write('\n');
    
            console.log("Write one line to " + messageFile);
        };
    
        // Invoke timeOutFunction every 3 seconds.
        setInterval(timeOutFunction, 3000);
    }
    
    // Run write data to message file function.
    writeDataToMessageFile();
  4. readData.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Get Data From Http Server</title>
    </head>
    
    <script>
        window.onload = function() {
            // Get the ul html web element.
            var ulList = document.getElementById("messageList");
    
            // Get the new event source object.
            var eventSource = new EventSource("http://localhost:8888/events");
    
            // When the event source send data back.
            eventSource.onmessage = function(event) {
    
                // Create a new li.
                var newElement = document.createElement("li");
    
                // Set li data.
                newElement.innerHTML = event.data;
    
                // Insert the li node.
                ulList.insertNode(newElement);
            }
        }
    </script>
    
    <body>
    <ul id="messageList"></ul>
    </body>
    </html>

3. Example Execute Steps.

  1. Run httpServer.js in node server.
  2. Copy readData.html to node server root folder.
  3. Open a web browser and browse url http://localhost:8888/readData.html.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x