Node.jsでファイルの更新を監視するには、fs.watchFile()を使います。
var fs = require('fs');
var http = require('http');
fs.watchFile('message.txt', function(curr, prev) {
console.log('現在の更新:' + curr.mtime);
console.log('前の更新:' + prev.mtime);
});
http.createServer(function(req, res) {
res.writeHead(200);
res.end('fs.watchFile() test');
}).listen(3000);
console.log('server started.');
空のmessage.txtを作ります。
$ echo '' > message.txt
Nodeを起動します。
$ node app.js &
message.txt に追記してみましょう。
$ echo 'Hello World!' >> message.txt $ 現在の更新:Tue Feb 21 2012 23:03:20 GMT+0900 (JST) 前の更新:Tue Feb 21 2012 23:02:14 GMT+0900 (JST) $
前回のファイル情報と、更新後のファイル情報を参照できます。
業務アプリケーションの連携なかではCSVファイルを特定のフォルダに保存してデータをやりとりするのもしばしば。意外と使えるかもしれません。ファイル変更をsocket.ioで通知したらもっと面白そうです。
0 件のコメント:
コメントを投稿