使用node.js观察文件更改 [英] Observe file changes with node.js

查看:82
本文介绍了使用node.js观察文件更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下UseCase:

I have the following UseCase:

A创建一个聊天并邀请B和C-在服务器A上创建一个 文件. A,B和C将消息写入此文件. A,B和C都读过 文件.

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.

我想在服务器上创建一个文件,并观察该文件是否有人在该文件中写入内容,然后通过websockets将新内容发送回去.

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.

因此,我的node.js应用程序应观察到此文件的任何更改.

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

如何观察文件更改?可以在不锁定文件的情况下使用节点js吗?

如果无法使用文件,则可以使用数据库对象(NoSQL)

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

推荐答案

好消息是您可以使用Node的API来观察文件更改.

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

弄清楚这些事情时,阅读Node.js API文档非常有用. 这是非常宝贵的资源. :)

Reading the Node.js API doc is very useful when figuring these things out. It's an invaluable source. :)

但是,这不能让您访问已写入文件的内容. 您也许可以使用fs.appendFile();函数,以便在将某些内容写入文件时,您会向其他事件发出事件,从而记录"正在写入的新数据.

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():直接从文档粘贴

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

在此处阅读有关fs.watch()的信息;功能

编辑:您可以使用该功能

fs.watchFile(); 

在此处阅读有关fs.watchFile()的信息;功能

这将使您可以查看文件中的更改. IE.只要它被任何其他类型的其他进程访问.

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

这篇关于使用node.js观察文件更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆