Init project
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
const chokidar = require('chokidar');
|
||||
const path = require('path');
|
||||
|
||||
function startWatcher({ inputFile, inputDir, server }) {
|
||||
const isDir = !!inputDir;
|
||||
// Watch the directory or the single file
|
||||
const watchTarget = isDir ? path.resolve(inputDir) : path.resolve(inputFile);
|
||||
|
||||
const watcher = chokidar.watch(watchTarget, {
|
||||
persistent: true,
|
||||
ignoreInitial: true,
|
||||
ignored: /(^|[/\\])\../, // ignore hidden files
|
||||
usePolling: true,
|
||||
interval: 500,
|
||||
});
|
||||
|
||||
let debounceTimer = null;
|
||||
|
||||
function isMd(filePath) {
|
||||
return /\.md$/i.test(filePath);
|
||||
}
|
||||
|
||||
function schedule(filePath) {
|
||||
// In dir mode, only react to .md files
|
||||
if (isDir && filePath && !isMd(filePath)) return;
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(() => {
|
||||
server.rebuild(filePath);
|
||||
}, 80);
|
||||
}
|
||||
|
||||
watcher.on('change', schedule);
|
||||
watcher.on('add', (filePath) => {
|
||||
if (!isDir || isMd(filePath)) {
|
||||
console.log(` + Nouveau fichier : ${path.basename(filePath)}`);
|
||||
schedule(filePath);
|
||||
}
|
||||
});
|
||||
watcher.on('unlink', (filePath) => {
|
||||
if (!isDir || isMd(filePath)) {
|
||||
console.log(` - Supprimé : ${path.basename(filePath)}`);
|
||||
schedule(null);
|
||||
}
|
||||
});
|
||||
|
||||
// Re-watch single file if recreated via temp+rename (some editors)
|
||||
if (!isDir) {
|
||||
watcher.on('unlink', () => {
|
||||
setTimeout(() => watcher.add(path.resolve(inputFile)), 300);
|
||||
});
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
watcher.close();
|
||||
server.server.close();
|
||||
console.log('\n👋 Au revoir !');
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { startWatcher };
|
||||
Reference in New Issue
Block a user