How to use watch - 10 common examples

To help you get started, we’ve selected a few watch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github julianburr / sketch-test-inspector / lib / index.js View on Github external
return new Promise((resolve, reject) => {
    // We write sketch actions to a specitic file, so we can listen to this file
    // to know in node when an action has been fired
    watch.createMonitor(ACTIONS_FOLDER_PATH, monitor => {
      monitor.on('created', () => {
        // NOTE: for some reason the action API doesn't work when running a plugin
        // from anywhere else than the plugin folder, so we cannot rely on it to
        // resolve the promise
        //
        // TODO: find alternative way!
        //
        // saveDocument();
        // setTimeout(() => {
        //   resolve();
        //   monitor.stop();
        // }, 200);
      });

      // Run command with current plugin and given identifier
      sketchtool.runPluginWithIdentifier(
github pgte / procmon / file_watch.js View on Github external
function fileWatch(monitorPath, remote) {
  var monitor;
  // start watch
  file.walk(monitorPath, onFileWalk);

  watch.createMonitor(monitorPath, function(_monitor) {
    monitor = _monitor;
    monitor.on('created', function(f, stat) {
      f = resolvePath(f);
      console.log('file added:', f);
      if (validFile(f) && ! stat.isDirectory()) {
        remote.emit('file added', f);
      }
    });

    monitor.on('removed', function(f) {
      f = resolvePath(f);
      if (validFile(f)) remote.emit('file removed', f);
    });

  });
github JetBrains / ring-ui / tools / watch-doc.js View on Github external
};

function runScript(scriptPath, args, callback) {
  var process = childProcess.fork(scriptPath, args);

  process.on('error', callback);

  process.on('exit', function (code) {
    var err = code === 0 ? null : new Error('exit code ' + code);
    callback(err);
  });
}

var isAlreadyGenerating = false;

watch.watchTree(watchPath, watchOptions, function onChange(file, curr, prev) {

  if (typeof file === 'string' && prev !== null && curr !== null && curr.nlink !== 0) {
    // file was changed
    var fileName = file.match(/[\w.-]+$/)[0];
    console.log('File changed:', fileName);

    if (isAlreadyGenerating){
      console.log('Documentation generation is in progress, change skipped');
      return;
    }

    isAlreadyGenerating = true;
    runScript(path.resolve(__dirname, './generate-documentation.js'), [fileName], function (err) {
      isAlreadyGenerating = false;
      if (err) {
        console.log(err);
github davidmurdoch / shopify-theme-sync / app.js View on Github external
function watchShop ( shopConfig ) {
	var directory = shopConfig.directory;
	if ( directory ) {
		if ( fs.existsSync( directory ) ) {

			var shopify = new ShopifySyncer( shopConfig ),
				shopOptions = shopConfig.options;

			console.log( util.format( "Walking directory tree: %s\n", directory) );

			watch.watchTree( directory, shopOptions, function sync( f, curr, prev ) {
				if ( typeof f == "object" && prev === null && curr === null ) {
					// we're done walking!

					console.log( util.format( "Now watching directory tree: %s\n", directory ).rainbow );
				}

				// we can't actually delete the root (at Shopify), so don't try.
				else if ( f !== directory ) {

					// `walk` sometimes lets dot files through (usually on creation), so we need to double check.
					if ( shopOptions.ignoreDotFiles && path.basename(f)[0] === "." ) {
						console.log( util.format( "dotFile file ignored: %s\n", f ) );
						return;
					}

					// `walk` sometimes lets filtered files through (usually on creation), so we need to double check.
github google / clasp / src / commands / push.ts View on Github external
export default async (cmd: { watch: boolean; force: boolean }) => {
  await checkIfOnline();
  await loadAPICredentials();
  await isValidManifest();
  const { rootDir } = await getProjectSettings();

  if (cmd.watch) {
    console.log(LOG.PUSH_WATCH);
    const patterns = await DOTFILE.IGNORE();
    /**
     * @see https://www.npmjs.com/package/watch
     */
    // TODO check alternative https://github.com/paulmillr/chokidar
    watchTree(rootDir || '.', async (f, curr, prev) => {
      // The first watch doesn't give a string for some reason.
      if (typeof f === 'string') {
        console.log(`\n${LOG.PUSH_WATCH_UPDATED(f)}\n`);
        if (multimatch([f], patterns, { dot: true }).length) {
          // The file matches the ignored files patterns so we do nothing
          return;
        }
      }
      if (!cmd.force && (await manifestHasChanges()) && !(await confirmManifestUpdate())) {
        console.log('Stopping push...');
        return;
      }
      console.log(LOG.PUSHING);
      pushFiles();
    });
  } else {
github partageit / vegetables / lib / serve.js View on Github external
logger.success('Vegetables started, at this address: localhost:' + config.port);
	logger.info('It is available %s', (config.host ? 'from this computer only' : 'from your network'));

	require('./generate')(argv, true, function(err) {
		if (err) {
			logger.error('First regeneration finished with errors');
		}
		if (config.serveAutoOpen) {
			openBrowser('http://localhost:' + config.port);
		}
		logger.info('Waiting for file updates...');
	});

	var firstTime = true;
	// and watch:
	watch.watchTree(
		'.',
		{
			'ignoreDotFiles': true,
			'ignoreUnreadableDir': true,
			'filter': function(file) {
				// watch template, root, not .vegetables
				if (['.vegetables', 'node_modules'].indexOf(file.split(path.sep)[0]) !== -1) {
					return false;
				}
				logger.debug('Watched file:', file);
				return true;
			}
		},
		function (f) {
			if (firstTime) {
				firstTime = false;
github kupriyanenko / jsttojs / lib / jsttojs.js View on Github external
compile: function(options, callback) {
    this.options = options;
    this.createWalker(callback);

    if (this.options.watch) {
      console.log(moment().format('[[]h:mm:ss YYYY-D-MM[]] ') + 'watch start...');

      watch.watchTree(this.options.root, {
          interval: 1000
        }, function (f, curr, prev) {
        if (typeof f == 'object' && prev === null && curr === null) {
          // Finished walking the tree
        } else {
          this.createWalker(callback);
        }
      }.bind(this));
    }
  }
}
github dmix / duster.js / duster.js View on Github external
// compile and save
      var compiled = dust.compile(String(data), templateId);
      
      var dirname = path.dirname(output_path);
      if (!fs.existsSync(dirname)) {
        fs.mkdirSync(dirname);
      }

      fs.writeFile(output_path, compiled, function(err) {
        if (err) throw err;
        console.log('Saved ' + output_path);
      });
    });
  }

  watch.createMonitor(input_path, {
    persistent: true,
    interval: 100
  }, function (monitor) {
    console.log("Watching " + input_path);
    monitor.files = ['*.dust', '*/*'];
    monitor.on("created", function (f, stat) {
      if (fs.lstatSync(f).isDirectory()) {
        return;
      }
      compile_dust(f);
    });
    monitor.on("changed", function (f, curr, prev) {
      if (fs.lstatSync(f).isDirectory()) {
        return;
      }
      compile_dust(f);
github julianburr / sketch-plugin-boilerplate / scripts / plugin / start.js View on Github external
fs.outputJson(paths.build + '/manifest.json', manifest);

    // Copy framework
    console.log('Copy satchel framework');
    fs.emptyDirSync(paths.build + '/Satchel.framework');
    fs.copySync(paths.framework, paths.build + '/Satchel.framework');

    // Done :)
    console.log(chalk.green('✓ Compiled successfully.'));
    console.log();

    // Start watching
    if (!watching) {
      console.log('Start watching...');
      watching = true;
      watch.createMonitor(paths.src, function (monitor) {
        monitor.on("created", build);
        monitor.on("changed", build);
        monitor.on("removed", build);
      });
    }
  }).catch(function (e) {
    // Catch any possible parse errors
github coreybutler / fenix / src / lib / api / server.js View on Github external
monitor: function(){
    var watch = require('watch'), me = this;
    watch.createMonitor(require('path').resolve(this.path),function(monitor){
      monitor.on("created", function (filename, stat) {
        if (!me.running)
          return; // Ignore if the server isn't running
        /**
         * @event filecreated
         * Fired when a new file is created in the server directory (recursive)
         */
        me.emit('filecreated',{filename:filename,server:me});
        me.syslog.log((filename+' created.'));
      });
      monitor.on("changed", function (filename, curr, prev) {
        if (!me.running)
          return; // Ignore if the server isn't running
        /**
         * @event fileupdated
         * Fired when a file is modified somewhere in the server directory (recursive)

watch

Utilities for watching file trees.

Apache-2.0
Latest version published 8 years ago

Package Health Score

68 / 100
Full package analysis