Skip to content

Instantly share code, notes, and snippets.

@zamber
Created August 23, 2019 20:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zamber/873dc2ba0926636a1bf03c6d33d80e85 to your computer and use it in GitHub Desktop.
Save zamber/873dc2ba0926636a1bf03c6d33d80e85 to your computer and use it in GitHub Desktop.
This is a simple, 0-dependency script for debugging watchers. It watches files in a directory and logs changes to the console. That's it. Should work on any OS. Works with absolute and relative paths. Will break on access denied or cyclical symlinks. For debug use only.
#!/usr/bin/env node
const { performance } = require('perf_hooks')
const fs = require('fs')
const path = require('path')
const log = console.log
const warn = console.warn
const err = console.error
const perf_start = performance.now()
// funcs
const pathJoin = filePath => file => path.join(filePath, file)
const cwdJoin = pathJoin(process.cwd())
const mapFilesNested = filePath => {
if (fs.statSync(filePath).isFile()) return [filePath]
return fs
.readdirSync(filePath)
.map(bareFilename => path.join(filePath, bareFilename))
.map(mapFilesNested)
}
const flatten = arr => [].concat(...arr)
const deepFlatten = arr =>
flatten(arr.map(a => (Array.isArray(a) ? deepFlatten(a) : a)))
const mapFiles = path => deepFlatten(mapFilesNested(path))
const validatePath = filePath => {
const isAbs = filePath[0] === path.sep
if (isAbs && filePath.length < 7)
warn(`Watching top-level directories ${filePath} is discouraged`)
// return isAbs ? path.relative(path.sep, filePath) : cwdJoin(filePath)
return isAbs ? filePath : cwdJoin(filePath)
}
const getFileSize = file => {
try {
fs.statSync(file)['size']
} catch (error) {
warn(" couldn't get file size - moved or deleted...")
return 0
}
}
const round = num => Number(num).toFixed(2)
// conf
const args = process.argv.slice(process.argv.indexOf(__filename) + 1)
log(validatePath(args[0]))
const watchDir = args.length ? validatePath(args[0]) : process.cwd
const fileWatchLogFunc = file => () =>
log(
`${
args[0][0] === path.sep ? file : path.relative(__dirname, file)
} (${round(getFileSize(file) / 1024)}kB) changed`
)
try {
log(`Looking for files to watch in ${watchDir}`)
const allFiles = mapFiles(watchDir)
perf_end = performance.now()
log(
`Watch list collected in ${round(perf_end - perf_start)}ms, count: ${
allFiles.length
}. Watching...\n`
)
allFiles.forEach(file => fs.watchFile(file, fileWatchLogFunc(file)))
} catch (error) {
err(
'\nUsage:\n ./dirWatch.js [path]\n' +
'OOPSIE WOOPSIE!! Uwu We made a fucky wucky!! A wittle ' +
'fucko boingo! The code monkeys at our headquarters are ' +
'working VEWY HAWD to fix this!\n\nGuru Meditation\n\n',
error
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment