es-node-runner
Version:
Node runner that transpiles typescript or es modules using blazing fast ⚡ esbuild and restarts the process automatically on change. Suitable for node development server.
63 lines (62 loc) • 1.85 kB
JavaScript
import {watch} from 'chokidar';
import DEBUG from 'debug';
import {performance} from 'perf_hooks';
import {spawnOptions, watchOptions} from './config.js';
import {rebuild, initialBuild} from './transpiler.js';
import {logger} from './utils/index.js';
const debug = DEBUG('es-node-runner:watcher');
const {delay, restartCmd, clearTerminal, autoRestart} = spawnOptions;
function clearTerminalOutput() {
process.stdout.write('\x1Bc\x1B[3J');
debug(`Terminal output cleared`);
}
function restartSubProcess() {
global.SUB_PROCESS_RESTART_TIME = performance.now();
rebuild();
}
function restartOnChange(action) {
debug(`${action}`);
if (clearTerminal === true) {
clearTerminalOutput();
}
logger.alert(
`\n[Watcher]: ${action}\n` + `Sub process will restart after ${delay} ms\n`
);
restartSubProcess();
}
process.stdin.on('data', (data) => {
const cmd = data.toString().trimEnd();
switch (cmd) {
case restartCmd:
logger.alert(`\nreceived '${cmd}' cmd, restarting sub process...\n`);
restartSubProcess();
break;
case 'clear':
clearTerminalOutput();
break;
default:
logger.warn(`unrecognized '${cmd}' cmd`);
break;
}
});
export default autoRestart === false
? () => initialBuild()
: () => {
const watcher = watch(watchOptions.watch, {
ignoreInitial: true,
ignored: watchOptions.ignore,
});
watcher.on('ready', () => {
debug('ready to watch for file changes');
logger.alert('[Watcher]: Watching for file changes\n');
initialBuild();
watcher
.on('change', (path) => {
restartOnChange(`${path} was changed`);
})
.on('error', (error) => {
debug(`watcher error - ${error}`);
console.log(`error - ${error}`);
});
});
};