UNPKG

1.86 kBJavaScriptView Raw
1/**
2 * Watch files.
3 * @memberof module:ape-watching/lib
4 * @function watchFiles
5 * @param {string|string} - Filenames to watch.
6 * @param {object} [options] - Optional settings.
7 * @param {string} [options.cwd] - Working directory path.
8 * @param {function} handler - File change handler.
9 */
10
11"use strict";
12
13var argx = require('argx'),
14 fs = require('fs'),
15 path = require('path'),
16 fwatcher = require('fwatcher'),
17 arrayfilter = require('arrayfilter'),
18 colorprint = require('colorprint'),
19 expandglob = require('expandglob');
20
21/** @lends watchFiles */
22function watchFiles(filenames, options, handler) {
23 var args = argx(arguments);
24 handler = args.pop('function') || argx.noop;
25 filenames = args.shift('string|array');
26 options = args.pop('object') || {};
27
28 var cwd = options.cwd || process.cwd();
29 filenames = expandglob.sync(filenames, {
30 cwd: cwd
31 }).map(function(filename){
32 return path.resolve(cwd, filename);
33 }).filter(fs.existsSync);
34 colorprint.info('[watchFiles] Start watch files...');
35 colorprint.trace('%s', filenames);
36
37 return filenames.map(function (filename) {
38 return _watchSingle(filename, options, handler);
39 }).filter(arrayfilter.emptyReject());
40}
41
42function _watchSingle(filename, options, listener) {
43 if (!fs.existsSync(filename)) {
44 return null;
45 }
46 var watcher = fwatcher(filename, options, function (err, event) {
47 if (err) {
48 throw err;
49 }
50 colorprint.debug('[ape-watching] File changed: %s', path.relative(process.cwd(), filename));
51 if (listener) {
52 listener(event, filename);
53 }
54 });
55 watcher.close = function () {
56 watcher.off();
57 var _ = watcher._;
58 if (_) {
59 _.close();
60 }
61 };
62 return watcher;
63
64}
65
66module.exports = watchFiles;