Barte
Barte

Reputation: 306

Node.js watching a file

I want to print a message whenever the file that I am watching has changed. I am able to do that using console.log but I couldn't figure out how to do that using response.write or similar functions.

var counter = 0;
const
    http = require('http'),
    fs = require('fs'),
    filename = process.argv[2];

var server = http.createServer(function(request, response) {
    response.writeHead(200, { 'Content-Type' : 'text/plain' });
    counter = counter + 1;
    response.end('Hello client ' + Math.round(counter / 2));
});

server.on('listening', function() {
    var watcher = fs.watch(filename, function(){
    console.log('The file ' + filename + ' has just changed.');
    });
});

server.listen(8080);

Also, the reason why I have done that Math.round(counter / 2) is because counter is increasing by 2 each time a client is connected. I was wondering why this is happening and if there is a better technique to resolve this.

Upvotes: 0

Views: 535

Answers (3)

user2178244
user2178244

Reputation: 38

You can try node module chokidar https://github.com/paulmillr/chokidar it is a gread module for file watching

Upvotes: 0

chriskelly
chriskelly

Reputation: 7736

If you want to inform an end user that the file has change, for example in a web browser, then you have a number of options, including polling the server or using websockets.

I would recommend you take a look at Server Sent Events

It is easy to implement and there are npm module out there to make it even easier in node.js. e.g. npm sse

Upvotes: 1

Hamel Kothari
Hamel Kothari

Reputation: 737

For you to be able to do it using response.write it would need to be part of your server request handler function.

File events can occur independently of someone sending a request, so it's handling is independent to that of handling a request. Because of this, there is no associated request for you to write to.

If you want to keep track of all the file change events and then show it to the user whenever they do send a request, consider storing the information about changes in an object outside your handler functions and when the a request takes place, read that object to see if there have been changes and write a response based on it to the user.

Upvotes: 1

Related Questions