Created
November 25, 2023 21:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not ready for deeper paths.