Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observe file changes with node.js

Tags:

node.js

I have the following UseCase:

A creates a Chat and invites B and C - On the Server A creates a File. A, B and C writes messages into this file. A, B and C read this file.

I want a to create a file on server and observe this file if anybody else writes something into this file send the new content back with websockets.

So, any change of this file should be observed by my node.js application.

How can I observe files-changes? Is this possible with node js without locking the files?

If not possible with files, would it be possible with database object (NoSQL)

like image 332
Sam Avatar asked Dec 04 '12 07:12

Sam


People also ask

How do you view file changes in node JS?

To watch any changes that are made to the file system, we can use the fs module provided by node. js that provides a solution here. For monitoring a file of any modification, we can either use the fs. watch() or fs.

How can you watch a file for changes and log the filename after each change?

Using fs. watchfile. The built-in fs-watchFile method seems like a logical choice to watch for changes in our log file. The callback listener will be invoked each time the file is changed.

How do I view a JavaScript file?

JavaScript code is written in plain text, so you can use any popular file readers (Notepad and TextPad) or word processors (Microsoft Word or Apple Pages) to open JavaScript files. You only need to right-click on the JavaScript file and select the Open With..

How node js read the content of a file?

To get the contents of a file as a string, we can use the readFileSync() or readFile() functions from the native filesystem ( fs ) module in Node. js. The readFileSync() function is used to synchronously read the contents from a file which further blocks the execution of code in Nodejs.


1 Answers

Good news is that you can observe filechanges with Node's API.

This however doesn't give you access to the contents that has been written into the file. You can maybe use the fs.appendFile(); function so that when something is being written into the file you emit an event to something else that "logs" your new data that is being written.

fs.watch(): Directly pasted from the docs

fs.watch('somedir', function (event, filename) {     console.log('event is: ' + event);     if (filename) {         console.log('filename provided: ' + filename);     } else {         console.log('filename not provided');     } }); 

Read here about the fs.watch(); function

EDIT: You can use the function

fs.watchFile();  

Read here about the fs.watchFile(); function

This will allow you to watch a file for changes. Ie. whenever it is accessed by some other processes of any kind.

like image 126
Henrik Andersson Avatar answered Oct 11 '22 11:10

Henrik Andersson