@dmail/filesystem-watch

2.8.0 • Public • Published

filesystem watch

npm package build codecov

Watch changes on your filesystem, either in a folder or on a specific file.

Introduction

@dmail/filesystem-watch has the following exports.

  • registerFolderLifecycle
  • registerFileLifecycle

registerFolderLifecycle example

registerFolderLifecycle is meant to be used when you need to something in sync with a given folder contents.

import { registerFolderLifecycle } from "@dmail/filesystem-watch"

const folderContentMap = {}
registerFolderLifecycle("/Users/you/folder", {
  added: ({ relativePath, type ) => {
    folderContentMap[relativePath] = type
  },
  removed: ({ relativePath }) => {
    delete folderContentMap[relativePath]
  },
})

— see registerFolderLifecycle documentation

registerFileLifecycle example

registerFileLifecycle is meant to be used when you need to do something in sync with a given file content.

import { readFileSync } from "fs"
import { registerFileLifecycle } from "@dmail/filesystem-watch"

const path = "/Users/you/folder/config.js"
let currentConfig = null
registerFileLifecycle(path, {
  added: () => {
    currentConfig = JSON.parse(String(readFileSync(path)))
  },
  updated: () => {
    currentConfig = JSON.parse(String(readFileSync(path)))
  },
  removed: () => {
    currentConfig = null
  },
})

— see registerFileLifecycle documentation

Installation

npm install @dmail/filesystem-watch@2.4.0

Why ?

I needed something capable to watch file changes on the filesystem.

The documentation of fs.watch makes it clear that you cannot really use it directly because it has several limitations specific to the filesystem.

Then I tried chokidar, a wrapper around fs.watch. However I could not fully understand what chokidar was doing under the hood.

What I needed was small wrapper around fs.watch that do not shallow events sent by the operating system. Ultimately chokidar could maybe do what I need but it's a bit too big for my use case.

— see fs.watch documentation
— see chokidar on github

fs.watch caveats

Everywhere:

  • Writing a file emits a change as chunk gets written in the file.
  • Trigger change on folder when something inside folder changes
  • might send event with filename being null (never reproduced yet)

On mac:

  • Trigger rename instead of change when updating a file

On linux:

  • recursive option not supported

On windows:

  • filesystem emits nothing when a file is removed
  • removing a watched folder throw with EPERM error

Readme

Keywords

none

Package Sidebar

Install

npm i @dmail/filesystem-watch

Weekly Downloads

28

Version

2.8.0

License

MIT

Unpacked Size

138 kB

Total Files

14

Last publish

Collaborators

  • dmail