Skip to content

Commit

Permalink
Fallback handling improved.
Browse files Browse the repository at this point in the history
  • Loading branch information
gavoja committed May 16, 2016
1 parent f0e2f28 commit 2a54920
Showing 1 changed file with 36 additions and 23 deletions.
59 changes: 36 additions & 23 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,48 +9,61 @@ const PLATFORMS = ['win32', 'darwin']
let watchFolder = (workingDir, recursive, callback) => {
let options = { persistent: true, recursive: recursive }

fs.watch(workingDir, options, (event, fileName) => {
let w = fs.watch(workingDir, options, (event, fileName) => {
callback(path.join(workingDir, fileName))
})

w.on('error', (e) => {
w.close()
})
}

// Attach watchers recursively.
// This code is synchronous in order to be able tell when it actuall ends.
let watchFolderFallback = (parent, callback) => {
// Skip if not a directory.
if (!fs.statSync(parent).isDirectory()) {
return
}

fs.stat(parent, (err, stats) => {
if (err || !stats.isDirectory()) {
// This code is synchronous to be able to tell when it actually finishes.
try {
// Skip if not a directory.
if (!fs.statSync(parent).isDirectory()) {
return
}

watchFolder(parent, false, callback)

// Iterate over list of children.
fs.readdir(parent, (err, children) => {
if (err) {
return
}

children.forEach((child) => {
child = path.resolve(parent, child)
watchFolderFallback(child, callback)
})
fs.readdirSync(parent).forEach((child) => {
child = path.resolve(parent, child)
watchFolderFallback(child, callback)
})
})
} catch (err) {
console.error(err)
}
}

let watch = (workingDir, callback) => {
workingDir = path.resolve(workingDir)

let cache = {}

if (PLATFORMS.indexOf(process.platform) !== -1) {
watchFolder(workingDir, true, callback)
} else {
watchFolderFallback(workingDir, callback)
return watchFolder(workingDir, true, callback)
}

watchFolderFallback(workingDir, (localPath) => {
fs.stat(localPath, (err, stat) => {
// Delete cache entry.
if (err) {
delete cache[localPath]
return
}

// Add new handler for new directory and save in cache.
if (stat.isDirectory() && !cache[localPath]) {
cache[localPath] = true
watchFolder(localPath, false, callback)
}
})

callback(localPath)
})
}

module.exports = watch

0 comments on commit 2a54920

Please sign in to comment.