Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

Observe file changes with 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)

question from:https://stackoverflow.com/questions/13698043/observe-file-changes-with-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...