inotify

repository·master·Indexed 42 days ago

https://github.com/c4milo/node-inotify

Node.js wrapper for the Linux inotify API, providing bindings for the v8 JavaScript engine to monitor file system events such as creation, modification, deletion, and movement in real-time. Version 1.4.6 supports Node.js versions 4.x.x through 11.x.x.

Tokens
2.3K
Snippets
4
Records
6
Agent score
4%

What's inside inotify

  1. Install node-inotify via NPM or Git

    master

    You can install inotify directly from NPM or build it from the source using node-gyp. Supported Node.js versions are 4.x.x up to 11.x.x.

    Install from NPM

    $ npm install inotify

    Install from git

    If installing from source, ensure node-gyp is installed globally.

    $ npm install node-gyp -g
    $ git clone git://github.com/c4milo/node-inotify.git
    $ cd node-inotify
    $ node-gyp rebuild
    $ npm install inotify
  2. Example: Monitoring file and directory events

    master

    This example demonstrates how to initialize Inotify, define a callback to handle different event types using bitwise operators, and set up watches on specific paths.

    var Inotify = require('inotify').Inotify;
    var inotify = new Inotify(); //persistent by default, new Inotify(false) //no persistent
    
    var data = {}; //used to correlate two events
    
    var callback = function(event) {
        var mask = event.mask;
        var type = mask & Inotify.IN_ISDIR ? 'directory ' : 'file ';
        if (event.name) {
            type += ' ' + event.name + ' ';
        } else {
            type += ' ';
        }
    
        if (mask & Inotify.IN_ACCESS) {
            console.log(type + 'was accessed ');
        } else if (mask & Inotify.IN_MODIFY) {
            console.log(type + 'was modified ');
        } else if (mask & Inotify.IN_OPEN) {
            console.log(type + 'was opened ');
        } else if (mask & Inotify.IN_CLOSE_NOWRITE) {
            console.log(type + ' opened for reading was closed ');
        } else if (mask & Inotify.IN_CLOSE_WRITE) {
            console.log(type + ' opened for writing was closed ');
        } else if (mask & Inotify.IN_ATTRIB) {
            console.log(type + 'metadata changed ');
        } else if (mask & Inotify.IN_CREATE) {
            console.log(type + 'created');
        } else if (mask & Inotify.IN_DELETE) {
            console.log(type + 'deleted');
        } else if (mask & Inotify.IN_DELETE_SELF) {
            console.log(type + 'watched deleted ');
        } else if (mask & Inotify.IN_MOVE_SELF) {
            console.log(type + 'watched moved');
        } else if (mask & Inotify.IN_IGNORED) {
            console.log(type + 'watch was removed');
        } else if (mask & Inotify.IN_MOVED_FROM) {
            data = event;
            data.type = type;
        } else if (mask & Inotify.IN_MOVED_TO) {
            if ( Object.keys(data).length &&
                data.cookie === event.cookie) {
                console.log(type + ' moved to ' + data.type);
                data = {};
            }
        }
    }
    
    var home_dir = {
        path:      '/home/camilo',
        watch_for: Inotify.IN_OPEN | Inotify.IN_CLOSE,
        callback:  callback
    };
    
    var home_watch_descriptor = inotify.addWatch(home_dir);
    
    var home2_dir = {
        path:      '/home/bob',
        watch_for: Inotify.IN_ALL_EVENTS,
        callback:  callback
    };
    
    var home2_wd = inotify.addWatch(home2_dir);
  3. Use the Inotify class API

    master

    The Inotify class provides methods to manage file system watches.

    • new Inotify([persistent]): Creates a new instance. Defaults to persistent mode. Pass false for non-persistent mode.
    • addWatch(arg): Adds a watch for a file or directory. Returns a watch descriptor (integer).
      • arg.path: Path to monitor.
      • arg.watch_for: An OR'ed set of events (e.g., Inotify.IN_ALL_EVENTS). Defaults to Inotify.IN_ALL_EVENTS.
      • arg.callback: Function receiving the event object.
    • removeWatch(watch_descriptor): Removes a watch. Returns true if successful, false otherwise. Removing a watch triggers an Inotify.IN_IGNORED event.
    • close(): Removes all watches and closes the inotify file descriptor. Returns true if successful, false otherwise.

    Note: Monitoring of directories is not recursive. To monitor subdirectories, you must create additional watches for each subdirectory.

    var Inotify = require('inotify').Inotify;
    var inotify = new Inotify(); // persistent by default
    
    var wd = inotify.addWatch({
        path: '.',
        watch_for: Inotify.IN_ALL_EVENTS,
        callback: function (event) {
            console.log('Event received:', event);
        }
    });
    
    // Later, remove the watch
    inotify.removeWatch(wd);
  4. Reference Inotify event masks (Watch for)

    master

    Use these constants to specify which events to monitor in the watch_for option of addWatch() or to check the event.mask in your callback.

    ConstantDescription
    Inotify.IN_ACCESSFile was accessed (read)
    Inotify.IN_ATTRIBMetadata changed (permissions, timestamps, etc.)
    Inotify.IN_CLOSE_WRITEFile opened for writing was closed
    Inotify.IN_CLOSE_NOWRITEFile not opened for writing was closed
    Inotify.IN_CREATEFile/directory created in the watched directory
    Inotify.IN_DELETEFile/directory deleted from the watched directory
    Inotify.IN_DELETE_SELFWatched file/directory was deleted
    Inotify.IN_MODIFYFile was modified
    Inotify.IN_MOVE_SELFWatched file/directory was moved
    Inotify.IN_MOVED_FROMFile moved out of the watched directory
    Inotify.IN_MOVED_TOFile moved into watched directory
    Inotify.IN_OPENFile was opened
    Inotify.IN_ALL_EVENTSWatch for all kinds of events
    Inotify.IN_CLOSEAlias for (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)
    Inotify.IN_MOVEAlias for (IN_MOVED_FROM | IN_MOVED_TO)
  5. Reference Inotify additional flags and mask bits

    master

    Additional Flags

    Used when setting up a watch via addWatch():

    • Inotify.IN_ONLYDIR: Only watch the path if it is a directory.
    • Inotify.IN_DONT_FOLLOW: Do not follow symbolic links.
    • Inotify.IN_ONESHOT: Only send events once.
    • Inotify.IN_MASK_ADD: Add (OR) events to the existing watch mask instead of replacing it.

    Event Mask Bits

    These bits may be set in the event.mask property returned in the callback:

    • Inotify.IN_IGNORED: Watch was removed (explicitly or automatically via deletion/unmount).
    • Inotify.IN_ISDIR: The subject of the event is a directory.
    • Inotify.IN_Q_OVERFLOW: Event queue overflowed (the watch descriptor will be -1).
    • Inotify.IN_UNMOUNT: The file system containing the watched object was unmounted.
  6. Understand the Inotify event object structure

    master

    When a callback is triggered, it receives an event object with the following properties:

    • watch: The watch descriptor associated with the event.
    • mask: A bitmask representing the events that occurred.
    • cookie: A value used to associate related events (e.g., for move operations).
    • name: (Optional) The name of the object being watched, relative to the watched directory. This is only present when an event occurs for a file inside a watched directory.
    var event = {
        watch: Watch descriptor,
        mask: Mask of events,
        cookie: Cookie that permits to associate events,
        name: Optional name of the object being watched
    };