How to use the chokidar.watch function in chokidar

To help you get started, we’ve selected a few chokidar 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 facebook / metro / scripts / watch.js View on Github external
getPackages().forEach(p => {
  const srcDir = path.resolve(p, 'src');
  try {
    fs.accessSync(srcDir, fs.F_OK);
    chokidar
      .watch(path.resolve(p, 'src'), {ignoreInitial: true})
      .on('all', (event, filename) => {
        const filePath = path.resolve(srcDir, filename);

        if ((event === 'add' || event === 'change') && exists(filePath)) {
          // eslint-disable-next-line no-console
          console.log(chalk.green('->'), `${event}: ${filename}`);
          rebuild(filePath);
        } else if (event === 'unlink') {
          const buildFile = path.resolve(srcDir, '..', 'build', filename);
          try {
            fs.unlinkSync(buildFile);
            process.stdout.write(
              chalk.red('  \u2022 ') +
                path.relative(path.resolve(srcDir, '..', '..'), buildFile) +
                ' (deleted)' +
github samueleaton / screwy / src / scripts / watchConfig.js View on Github external
function createFileWatcher(pattern, command) {
	// default task is 'START' // check for blank spaces
	if ((/ /g).test(command) === false)
		command = 'START ' + command;

	const task = getTask(command);

	if (!task || !taskFunctionMap[task])
		return logger(invalidCommandMsg(command));

	const fileWatcher = chokidar.watch(pattern);
	const func = taskFunctionMap[task];
	const npmScript = command.slice(task.length).trim();
	
	fileWatcher.on('change', path => func(npmScript));
}
github GitOfZGT / zero-design / zerod-webpack-conf / build / copy.js View on Github external
});
};
const copyFrom = `./${config.copyFolderName}`;
// 复制目录
var myCopy = function() {
    if (!fs.existsSync(copyFrom)) {
        return;
    }
    exists(copyFrom, './node_modules/' + config.copyName, copy);
};
if (config.copyName) {
    myCopy();
    var args = process.argv.splice(2);
    if (args.includes('watchChange')) {
        var chokidar = require('chokidar');
        chokidar.watch(copyFrom).on('change', myCopy);
    }
}
module.exports = myCopy;
github ulver2812 / aws-s3-backup / src / app / providers / job-scheduler.service.ts View on Github external
const cronRule = this.cronService.getCronStringFromJobPeriod(job.period);
      scheduler = schedule.scheduleJob({start: startTime, end: endTime, rule: cronRule}, () => {
        this.awsService.s3Sync(job);
      });
    } else if (job.type === JobType.Live) {
      // LIVE JOB
      const watchedPath = [];
      job.files.forEach((item) => {
        watchedPath.push(item.path);
      });

      const lazyS3Sync = sugar.Function.lazy(() => {
        this.awsService.s3Sync(job);
      }, 10000, true, 2);

      scheduler = chokidar.watch(watchedPath, {awaitWriteFinish: true});

      scheduler.on('ready', () => {
        lazyS3Sync();
        scheduler.on('all', (path, event) => {
          lazyS3Sync();
        });
      });

      scheduler.on('error', (err) => {
        this.logService.printLog(LogType.ERROR, 'Can\'t run live sync for ' + job.name + ' because of: \r\n' + err);
        job.alert = true;
        this.jobService.save(job);
      });
    }

    if (scheduler === null) {
github medialab / website / wilson / preview.js View on Github external
console.log('wilson.preview: Watching SASS...');

    const compile = debounce(() => {
      console.log('wilson.preview: Compiling SASS...');

      this.compileAssets(err => {
        if (err) {
          console.error('wilson.preview: Error while compiling SASS:', err);
          return;
        }

        this.emit('sassCompiled');
      });
    }, 500);

    chokidar
      .watch(
        path.join(__dirname, '..', 'site', 'assets', 'scss', '**/*.scss'),
        {awaitWriteFinish: true, ignoreInitial: true}
      )
      .on('change', compile)
      .on('add', compile)
      .on('unlink', compile);
  }
github vtex / toolbelt / src / modules / apps / link.ts View on Github external
const mapLocalToBuiderPath = path => {
    const abs = resolvePath(root, path)
    for (const [module, modulePath] of moduleAndMetadata as any) {
      if (abs.startsWith(modulePath)) {
        return abs.replace(modulePath, join('.linked_deps', module))
      }
    }
    return path
  }

  const pathModifier = pipe(mapLocalToBuiderPath, path => path.split(sep).join('/'))

  const addIgnoreNodeModulesRule = (paths: Array boolean)>) =>
    paths.concat((path: string) => path.includes('node_modules'))

  const watcher = chokidar.watch([...defaultPatterns, ...linkedDepsPatterns], {
    atomic: stabilityThreshold,
    awaitWriteFinish: {
      stabilityThreshold,
    },
    cwd: root,
    ignoreInitial: true,
    ignored: addIgnoreNodeModulesRule(getIgnoredPaths(root)),
    persistent: true,
    usePolling: process.platform === 'win32',
  })

  return new Promise((resolve, reject) => {
    watcher
      .on('add', file => queueChange(file))
      .on('change', file => queueChange(file))
      .on('unlink', file => queueChange(file, true))
github flatpickr / flatpickr / build.js View on Github external
function watch(path, cb){
    chokidar.watch(path, {
        awaitWriteFinish: {
            stabilityThreshold: 100
        }
    })
    .on('change', cb)
    .on('error', logErr);
}
github elastic / kibana / src / dev / sass / build_sass.js View on Github external
if (watch) {
    const debouncedBuild = debounce(async path => {
      let buildPaths = styleSheetPaths;
      if (path) {
        buildPaths = styleSheetPaths.filter(styleSheetPath =>
          path.includes(styleSheetPath.urlImports.publicDir)
        );
      }
      await build({ log, kibanaDir, styleSheetPaths: buildPaths, watch });
    });

    const watchPaths = styleSheetPaths.map(styleSheetPath => styleSheetPath.urlImports.publicDir);

    await build({ log, kibanaDir, styleSheetPaths });

    chokidar.watch(watchPaths, { ignoreInitial: true }).on('all', (_, path) => {
      debouncedBuild(path);
    });
  } else {
    await build({ log, kibanaDir, styleSheetPaths });
  }
}
github Lapple / ErrorBoard / node_modules / watchify / index.js View on Github external
function watchFile_ (file) {
        if (!fwatchers[file]) fwatchers[file] = [];
        if (!fwatcherFiles[file]) fwatcherFiles[file] = [];
        if (fwatcherFiles[file].indexOf(file) >= 0) return;
        
        var w = chokidar.watch(file, {persistent: true});
        w.setMaxListeners(0);
        w.on('error', b.emit.bind(b, 'error'));
        w.on('change', function () {
            invalidate(file);
        });
        fwatchers[file].push(w);
        fwatcherFiles[file].push(file);
    }
github Pupix / lcu-connector / lib / index.js View on Github external
_initLockfileWatcher() {
        if (this._lockfileWatcher) {
            return;
        }

        const lockfilePath = path.join(this._dirPath, 'lockfile');
        this._lockfileWatcher = chokidar.watch(lockfilePath, { disableGlobbing: true });

        this._lockfileWatcher.on('add', this._onFileCreated.bind(this));
        this._lockfileWatcher.on('change', this._onFileCreated.bind(this));
        this._lockfileWatcher.on('unlink', this._onFileRemoved.bind(this));
    }

chokidar

Minimal and efficient cross-platform file watching library

MIT
Latest version published 3 months ago

Package Health Score

85 / 100
Full package analysis