gaze
:crystal_ball: A globbing fs.watch wrapper built from the best parts of other fine watch libs.
Top Related Projects
Quick Overview
Gaze is a file watching utility for Node.js. It provides a simple and efficient way to watch files and directories for changes, allowing developers to trigger actions when files are modified, added, or deleted.
Pros
- Easy to use API with both callback and promise-based interfaces
- Cross-platform compatibility (works on Windows, macOS, and Linux)
- Supports watching multiple files and directories simultaneously
- Configurable with options for filtering and debouncing events
Cons
- Limited documentation and examples
- Not actively maintained (last update was several years ago)
- May have performance issues with large directory structures
- Lacks some advanced features found in newer file watching libraries
Code Examples
- Basic file watching:
const gaze = require('gaze');
gaze('**/*', function(err, watcher) {
// On file changed
this.on('changed', function(filepath) {
console.log(filepath + ' was changed');
});
// On file added
this.on('added', function(filepath) {
console.log(filepath + ' was added');
});
// On file deleted
this.on('deleted', function(filepath) {
console.log(filepath + ' was deleted');
});
});
- Using promises:
const gaze = require('gaze');
gaze('**/*').then((watcher) => {
watcher.on('all', (event, filepath) => {
console.log(filepath + ' was ' + event);
});
});
- Watching specific file types:
const gaze = require('gaze');
gaze(['**/*.js', '**/*.css'], function(err, watcher) {
this.on('changed', function(filepath) {
console.log('JavaScript or CSS file changed: ' + filepath);
});
});
Getting Started
To use Gaze in your project, follow these steps:
-
Install Gaze using npm:
npm install gaze
-
Require Gaze in your Node.js script:
const gaze = require('gaze');
-
Start watching files or directories:
gaze('path/to/watch/**/*', function(err, watcher) { // Your file watching logic here });
Competitor Comparisons
Minimal and efficient cross-platform file watching library
Pros of Chokidar
- More actively maintained with frequent updates
- Better cross-platform compatibility, especially for Windows
- Offers more advanced features like atomic writes and symlink following
Cons of Chokidar
- Slightly more complex API compared to Gaze
- Larger package size due to additional dependencies
Code Comparison
Chokidar:
const chokidar = require('chokidar');
chokidar.watch('path/to/dir').on('all', (event, path) => {
console.log(event, path);
});
Gaze:
const gaze = require('gaze');
gaze('path/to/dir/**/*', function(err, watcher) {
this.on('all', function(event, filepath) {
console.log(event, filepath);
});
});
Both libraries provide file watching capabilities, but Chokidar offers a more streamlined API and better performance, especially in complex scenarios. Gaze, while simpler, may be sufficient for basic use cases. Chokidar's active development and broader feature set make it a more robust choice for most projects, particularly those requiring cross-platform compatibility or advanced file system monitoring.
Utilities for watching file trees in node.js
Pros of Watch
- Simpler API with fewer options, making it easier to use for basic file watching tasks
- Supports recursive watching of directories out of the box
- Lighter weight with fewer dependencies
Cons of Watch
- Less granular control over file watching behavior
- Fewer advanced features compared to Gaze (e.g., no debouncing or filtering options)
- Not actively maintained (last update was in 2019)
Code Comparison
Watch:
var watch = require('watch');
watch.createMonitor('/home/mikeal', function (monitor) {
monitor.on("created", function (f, stat) {
// Handle new files
})
monitor.on("changed", function (f, curr, prev) {
// Handle file changes
})
})
Gaze:
var gaze = require('gaze');
gaze('**/*', function(err, watcher) {
this.on('all', function(event, filepath) {
console.log(filepath + ' was ' + event);
});
this.on('changed', function(filepath) {
console.log(filepath + ' was changed');
});
});
Both libraries provide similar functionality for watching files and directories, but Gaze offers more advanced features and configuration options, while Watch focuses on simplicity and ease of use.
User-friendly glob matching
Pros of globby
- Supports newer Node.js versions and has more active maintenance
- Offers a Promise-based API for modern JavaScript practices
- Provides more extensive globbing features, including negation patterns
Cons of globby
- Lacks built-in file watching functionality
- May have a steeper learning curve for users familiar with simpler glob patterns
- Potentially higher memory usage for large file sets due to its comprehensive feature set
Code Comparison
gaze:
var gaze = require('gaze');
gaze('**/*', function(err, watcher) {
this.on('changed', function(filepath) {
console.log(filepath + ' was changed');
});
});
globby:
const globby = require('globby');
(async () => {
const paths = await globby(['**/*', '!node_modules']);
console.log(paths);
})();
Key Differences
- gaze focuses on file watching, while globby specializes in file matching
- globby uses Promise-based async/await syntax, whereas gaze uses callbacks
- gaze provides real-time file system monitoring, which globby does not offer out-of-the-box
- globby's pattern matching is more powerful, supporting advanced glob features
Use Cases
- Choose gaze for projects requiring live file system monitoring
- Opt for globby when you need powerful, flexible file matching without watching functionality
glob functionality for node.js
Pros of node-glob
- More comprehensive glob pattern support, including advanced features like brace expansion
- Higher performance for large file systems due to optimized algorithms
- Widely adopted and battle-tested in many popular projects
Cons of node-glob
- Lacks built-in file watching functionality
- More complex API, which may be overkill for simple use cases
- Slightly larger package size due to additional features
Code Comparison
node-glob:
const glob = require('glob');
glob('**/*.js', (err, files) => {
console.log(files);
});
gaze:
const gaze = require('gaze');
gaze('**/*.js', (err, watcher) => {
watcher.on('changed', (filepath) => {
console.log(filepath + ' was changed');
});
});
Key Differences
- node-glob focuses on file matching and pattern expansion
- gaze provides file watching capabilities out of the box
- node-glob has a callback-based API, while gaze uses an event-driven approach
- gaze is more suitable for tasks requiring real-time file system monitoring
- node-glob is better for one-time file lookups and complex pattern matching
Both libraries serve different primary purposes, with node-glob excelling at file matching and gaze specializing in file watching. The choice between them depends on the specific requirements of your project.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
gaze
A globbing fs.watch
wrapper built from the best parts of other fine watch libs.
Compatible with Node.js >= 4.x, Windows, macOS, and Linux.
Usage
Install the module with: npm install gaze
or place into your package.json
and run npm install
.
const gaze = require('gaze');
// Watch all .js files/dirs in process.cwd()
gaze('**/*.js', (err, watcher) => {
// Files have all started watching
// Get all watched files
const watched = watcher.watched();
// On file changed
watcher.on('changed', filepath => {
console.log(filepath + ' was changed');
});
// On file added
watcher.on('added', filepath => {
console.log(filepath + ' was added');
});
// On file deleted
watcher.on('deleted', filepath => {
console.log(filepath + ' was deleted');
});
// On changed/added/deleted
watcher.on('all', (event, filepath) => {
console.log(filepath + ' was ' + event);
});
// Get watched files with relative paths
const files = watcher.relative();
});
// Also accepts an array of patterns
gaze(['stylesheets/*.css', 'images/**/*.png'], () => {
// Add more patterns later to be watched
watcher.add(['js/*.js']);
});
Alternate Interface
const {Gaze} = require('gaze');
const gaze = new Gaze('**/*');
// Files have all started watching
gaze.on('ready', watcher => { });
// A file has been added/changed/deleted has occurred
gaze.on('all', (event, filepath) => { });
Errors
gaze('**/*', (error, watcher) => {
if (error) {
// Handle error if it occurred while starting up
}
});
// Or with the alternative interface
const gaze = new Gaze();
gaze.on('error', error => {
// Handle error here
});
gaze.add('**/*');
Minimatch / Glob
See isaacs's minimatch
for more
information on glob patterns.
Documentation
gaze([patterns, options, callback])
patterns
{String
|Array
} File patterns to be matchedoptions
{Object
}callback
{Function
}err
{Error
|null
}watcher
{Object
} Instance of theGaze
watcher
Class: gaze.Gaze
Create a Gaze
object by instancing the gaze.Gaze
class.
const Gaze = require('gaze').Gaze;
const gaze = new Gaze(pattern, options, callback);
Properties
options
The options object passed in.interval
{integer} Interval to pass tofs.watchFile
debounceDelay
{integer} Delay for events called in succession for the same file/event in millisecondsmode
{string} Force the watch mode. Either'auto'
(default),'watch'
(force native events), or'poll'
(force stat polling).cwd
{string} The current working directory to base file patterns from. Default isprocess.cwd()
.
Events
ready(watcher)
When files have been globbed and watching has begun.all(event, filepath)
When anadded
,changed
,renamed
, ordeleted
event occurs.added(filepath)
When a file has been added to a watch directory.changed(filepath)
When a file has been changed.deleted(filepath)
When a file has been deleted.renamed(newPath, oldPath)
When a file has been renamed.end()
When the watcher is closed and watches have been removed.error(err)
When an error occurs.nomatch
When no files have been matched.
Methods
emit(event, [...])
Wrapper forEventEmitter.emit
.added
|changed
|renamed
|deleted
events will also trigger theall
event.close()
Unwatch all files and reset the watch instance.add(patterns, callback)
Adds file(s)patterns
to be watched.remove(filepath)
Removes a file or directory from being watched. Does not recurse directories.watched()
Returns the currently watched files.relative([dir, unixify])
Returns the currently watched files with relative paths.dir
{string} Only return relative files for this directory.unixify
{boolean} Return paths with/
instead of\\
if on Windows.
Similar Projects
Other great watch libraries to try are:
Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using grunt.
Release History
- 1.1.3 - Fix for Node 10 support (@aredridel). Officially dropping support for Node < 4.
- 1.1.2 - Prevent more
ENOENT
errors from escaping (@alexgorbatchev). - 1.1.1 - Prevent
fs.watch
errors from escaping error handler (@rosen-vladimirov). Fix_addToWatched
withoutpath.sep
(@wyicwx). - 1.1.0 - Update to
globule@1.0.0
withminimatch >= 3.0.0
. - 1.0.0 - Revert back to 0.5.2. Drop support for Node.js v0.8. Fix for
maxListeners
. Updateglobule
to0.2.0
. - 0.6.4 - Catch and emit
error
fromreaddir
(@oconnore). Fix for0 maxListeners
. Usegraceful-fs
to avoidEMFILE
errors in other placesfs
is used. Better method to determine ifpathwatcher
was built. Fix keeping process alive too much, only initpathwatcher
if a file is being watched. Set min required to Windows Vista when building on Windows (@pvolok). - 0.6.3 - Add support for Node.js v0.11
- 0.6.2 - Fix argument error with
watched()
. Fix for erroneousadded
events on folders. Ignoremsvs
build error 4244. - 0.6.1 - Fix for absolute paths.
- 0.6.0 - Uses native OS events (fork of
pathwatcher
) but can fall back to stat polling. Everything is async to avoid blocking, includingrelative()
andwatched()
. Better error handling. Update toglobule@0.2.0
. No longer watchescwd
by default. Addedmode
option. BetterEMFILE
message. AvoidsENOENT
errors with symlinks. All constructor arguments are optional. - 0.5.2 - Fix for
ENOENT
error with non-existent symlinks [BACKPORTED]. - 0.5.1 - Use
setImmediate
(process.nextTick
for Node.js v0.8) to deferready
/nomatch
events (@amasad). - 0.5.0 - Process is now kept alive while watching files. Emits a
nomatch
event when no files are matching. - 0.4.3 - Track file additions in newly created folders (@brett-shwom).
- 0.4.2 - Fix
.remove()
method to remove a single file in a directory (@kaelzhang). Fixing âCannot call method 'call' of undefined
â (@krasimir). Track new file additions within folders (@brett-shwom). - 0.4.1 - Fix
watchDir
not respecting close in race condition (@chrisirhc). - 0.4.0 - Drop support for Node.js v0.6. Use
globule
for file matching. Avoid Node.js v0.10path.resolve
/join
errors. Register new files when added to non-existent folder. Multiple instances can now poll the same files (@jpommerening). - 0.3.4 - Code clean up. Fix â
path must be strings
â errors (@groner). Fix incorrectadded
events (@groner). - 0.3.3 - Fix for multiple patterns with negate.
- 0.3.2 - Emit
end
beforeremoveAllListeners
. - 0.3.1 - Fix
added
events within subfolder patterns. - 0.3.0 - Handle safewrite events,
forceWatchMethod
option removed, bug fixes and watch optimizations (@rgaskill). - 0.2.2 - Fix issue where subsequent
add
calls dont get watched (@samcday).removeAllListeners
onclose
. - 0.2.1 - Fix issue with invalid
added
events in current working dir. - 0.2.0 - Support and mark folders with
path.sep
. AddforceWatchMethod
option. Supportrenamed
events. - 0.1.6 - Recognize the
cwd
option properly - 0.1.5 - Catch â
too many open file
â errors - 0.1.4 - Really fix the race condition with 2 watches
- 0.1.3 - Fix race condition with 2 watches
- 0.1.2 - Read triggering changed event fix
- 0.1.1 - Minor fixes
- 0.1.0 - Initial release
License
Copyright (c) 2018 Kyle Robinson Young
Licensed under the MIT license.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot