UNPKG

@ainc/script

Version:

Script compiler for typescript

87 lines (68 loc) 2.09 kB
/** ***************************************** * Created by edonet@163.com * Created on 2021-06-27 16:00:15 ***************************************** */ 'use strict'; /** ***************************************** * 加载依赖 ***************************************** */ import { Stats } from 'fs'; import * as chokidar from 'chokidar'; /** ***************************************** * 监听对象 ***************************************** */ export interface Watcher extends chokidar.FSWatcher { waitExit(): Promise<void>; } /** ***************************************** * 监听回调 ***************************************** */ export interface Handler { (this: Watcher, type: 'add'|'addDir'|'change'|'unlink'|'unlinkDir', path: string, stats?: Stats): void; } /** ***************************************** * 配置 ***************************************** */ export interface Options extends chokidar.WatchOptions { handler?: Handler; } /** ***************************************** * 监听文件文件变更 ***************************************** */ export function watch(files: string | string[], handler?: Handler | Options): Watcher { const opts = typeof handler === 'function' ? { handler } : { ...handler }; const watcher = chokidar.watch(files, opts) as Watcher; const closeWatcher = watcher.close.bind(watcher); // 监听变更 if (typeof opts.handler === 'function') { watcher.on('all', opts.handler.bind(watcher)); } // 替换关闭函数 watcher.close = () => { const deferred = {} as { resolve(): void, reject(): void }; // 执行关闭事件 watcher.emit('close', new Promise( (resolve, reject) => Object.assign(deferred, { resolve, reject }) )); // 执行关闭 return closeWatcher().then(deferred.resolve, deferred.reject); }; // 等待结束 watcher.waitExit = () => { return new Promise(resolve => watcher.once('close', resolve)); }; // 返回监听对象 return watcher; }