Skip to content

Instantly share code, notes, and snippets.

@UniBreakfast
Created November 25, 2023 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UniBreakfast/abb94488439f31eabf2f2e87a3141793 to your computer and use it in GitHub Desktop.
Save UniBreakfast/abb94488439f31eabf2f2e87a3141793 to your computer and use it in GitHub Desktop.
A node.js function `watchFile(filePath, contentCallback)` that can handle path like `folder/file.ext` and is ready to folder and/or file not be there at any given point in time.
const { existsSync, watch, readFile } = require('fs');
const { dirname, basename } = require('path');
function watchFile(filePath, contentCallback) {
const folderPath = dirname(filePath);
const folderName = basename(folderPath);
const parentPath = dirname(folderPath);
const fileName = basename(filePath);
let folderExists = existsSync(folderPath);
let folderWatcher, fileWatcher;
function watchFolder() {
folderWatcher = watch(parentPath, (_, name) => {
if (name !== folderName) return;
if (existsSync(folderPath)) {
if (!folderExists) {
folderExists = true;
watchFileInFolder();
}
} else {
fileWatcher?.close();
fileWatcher = null;
folderExists = false;
if (!folderWatcher) watchFolder();
}
});
folderWatcher.on('error', (err) => {
if (err.code === 'EPERM') {
folderWatcher?.close();
folderWatcher = null;
}
});
}
function watchFileInFolder() {
fileWatcher = watch(folderPath, (_, name) => {
if (name != fileName) return;
readFile(filePath, 'utf8', (err, data) => {
contentCallback(err ? null : data);
});
});
fileWatcher.on('error', (err) => {
if (err.code === 'EPERM') {
fileWatcher?.close();
fileWatcher = null;
if (!folderWatcher) watchFolder();
}
});
}
folderExists ? watchFileInFolder() : watchFolder();
}
watchFile('a/d.e', console.log);
@UniBreakfast
Copy link
Author

It is not ready for deeper paths.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment