filesystem watch
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 ofchange
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