Node.JS FS.Watch Example

Node js method is used to monitor a file change event such as write data to file, delete data from 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 client browser.

1. Node JS FS Watch Example Overview.

This example will demonstrate below functions.

  1. Create a http server which will listen for client request and store server response object to a global variable. The global variable will be used to send changed file data back to client browser.
  2. Create a backend function which will write data to a file regularly.
  3. Monitor data file change event when data added to the text file and send the changed data back to client.

If you can not watch the above video, you can see it on the youtube URL

2. Node JS FS Watch Example Source Coe.

To use fs module watch function, you should first import fs module then run below code.

var fileSystem = require("fs");

// This is the fs watch function., function(event, filename) {

This example core files are httpServer.js, readData.html. The message text file is message.txt.

node js fs watch example source files

2.1 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;


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);, 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.
                // Send the text line back to client.
                clientUser.write(lineText + '\n\n');

                lineText = '';
                lineText += charactor;

            // Run sendMessageToClient function after while.
            return process.nextTick(function() {



// This function is used to monitor the message text file data change.
function watchFileDataChange() {, 'r', function(err, fd) {

        if(err) {
            return setTimeout(watchFileDataChange, 3000);

        // This is the fs watch function., function(event, filename) {

            // If data change then send new text back to client.
            if(event === "change") {



// Run watch file data change function.

// 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 ');

        console.log("Write one line to " + messageFile);

    // Invoke timeOutFunction every 3 seconds.
    setInterval(timeOutFunction, 3000);

// Run write data to message file function.

2.2 readData.html

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Get Data From Http Server</title>

    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 =;

            // Insert the li node.

<ul id="messageList"></ul>

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
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x