From 6a2609f0eb7f7873413201f2cc6957b41202328f Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Sun, 12 Apr 2015 11:27:24 +0100 Subject: [PATCH] feat(file-watcher): Add `.watch()` to public api --- index.js | 10 ++++++- test/specs/api/watch.js | 62 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 test/specs/api/watch.js diff --git a/index.js b/index.js index 0579429ae..a406cd782 100755 --- a/index.js +++ b/index.js @@ -83,6 +83,13 @@ module.exports.notify = noop("notify"); */ module.exports.exit = noop("exit"); +/** + * File watcher + * + * @method watch + */ +module.exports.watch = noop("watch"); + /** * Method to pause file change events * @@ -261,7 +268,8 @@ function create(name, emitter) { cleanup: browserSync.cleanup.bind(browserSync), use: browserSync.registerPlugin.bind(browserSync), getOption: browserSync.getOption.bind(browserSync), - emitter: browserSync.events + emitter: browserSync.events, + watch: require("./lib/file-watcher").watch }; Object.defineProperty(instance, "active", { diff --git a/test/specs/api/watch.js b/test/specs/api/watch.js new file mode 100644 index 000000000..94aaba4aa --- /dev/null +++ b/test/specs/api/watch.js @@ -0,0 +1,62 @@ +"use strict"; + +var browserSync = require("../../../"); +var path = require("path"); +var outpath = path.join(__dirname, "../../fixtures"); +var fs = require("graceful-fs"); + +var tempFileContent = "A test generated this file and it is safe to delete"; +var writeTimeout = 150; // Wait for it to get to the filesystem +var assert = require("assert"); + +var writeFileWait = function (name, content, cb) { + if (!cb) { + cb = function () { + }; + } + setTimeout(function () { + fs.writeFile(name, content, cb); + }, writeTimeout); +}; + +describe("API: .watch() - Public watch method", function () { + + it("Should allow arbitrary watchers with callback fn when not connected to running instance", function (done) { + + browserSync.reset(); + + var tempFile = path.join(outpath, "watch-func.txt"); + var bs = browserSync.create("test"); + + fs.writeFile(tempFile, tempFileContent, function () { + + var watcher = bs.watch(tempFile, {ignoreInitial: true}, function (event, file) { + assert.equal(event, "change"); + assert.equal(file, tempFile); + watcher.close(); + done(); + }); + + writeFileWait(tempFile, tempFileContent + " changed"); + }); + }); + + it("Should allow arbitrary watchers with event emitter fn when not connected to running instance", function (done) { + + browserSync.reset(); + + var tempFile = path.join(outpath, "watch-func.txt"); + var bs = browserSync.create("test"); + + fs.writeFile(tempFile, tempFileContent, function () { + + var watcher = bs.watch(tempFile, {ignoreInitial: true}).on("change", function (file) { + assert.equal(file, tempFile); + watcher.close(); + done(); + }); + + writeFileWait(tempFile, tempFileContent + " changed"); + }); + }); +});