Skip to content

Instantly share code, notes, and snippets.

@dliv
Last active January 13, 2017 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dliv/16b285d1c3ebde6f1966a122d4f492cc to your computer and use it in GitHub Desktop.
Save dliv/16b285d1c3ebde6f1966a122d4f492cc to your computer and use it in GitHub Desktop.
watch a group of files and, on change, touch a different file
// Example usage:
// node watch-and-touch 'src/**/*.post.css' src/styles-index.post.css
//
// Example will `touch` src/styles-index.post.css if any other css file
// under src changes. Potential usecase: webpack hot module reloading is
// working for your primary postcss file, but does not work for other
// postcss files imported from the main file.
//
// See: https://github.com/postcss/postcss-loader/issues/122
// See: https://github.com/postcss/postcss-import/issues/233
var chokidar = require('chokidar'); // "^1.6.1"
var Rx = require('rxjs'); // "5.0.0-rc.2"
const exec = require('child_process').exec;
var usage = 'node watch-and-touch file-glob-to-watch file-to-touch';
var example = "node watch-and-touch 'src/**/*.post.css' src/styles-index.post.css";
var watchPath = process.argv[2];
var touchPath = process.argv[3];
if (!(watchPath && touchPath)) {
console.error('Missing arguments');
console.log(`usage: ${usage}`);
console.log(`example: ${example}`);
process.exit(1);
}
var eventsOnWatchPath = new Rx.Subject();
// push relevant file system events to eventsOnWatchPath
chokidar.watch(watchPath, {
ignored: /[\/\\]\./,
persistent: true
}).on('all', (event, path) => eventsOnWatchPath.next({ event, path }));
function touch () {
exec(`touch ${touchPath}`, err => {
if (err) {
console.error(err);
} else {
console.log(`>>> touched ${touchPath}`);
}
});
}
eventsOnWatchPath
// don't recurse if touchPath is matched by watchPath
.filter(e => e.path !== touchPath)
// chokidar begins by emitting all files matching watchPath, skip that
.skipUntil(Rx.Observable.timer(100))
.do(e => console.log(`${e.event}: ${e.path}`))
.sampleTime(500)
.subscribe(touch);
console.log(`>> Watching ${watchPath}. Will touch ${touchPath} on changes.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment