UNPKG

ts-node-restarter

Version:

A cli tool for restarting your node.js server when files change

75 lines (74 loc) 2.73 kB
#!/usr/bin/env node "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const child_process_1 = __importDefault(require("child_process")); const parsePath = (pathName) => { return path_1.default.join(process.cwd(), pathName); }; const parseTargetScriptPath = () => { const args = process.argv; if (args.length !== 3) { console.log('can\'t find target script!'); process.exit(1); } const targetScriptName = args[2]; const targetScriptPath = parsePath(targetScriptName); return targetScriptPath; }; const parseConfig = () => { const configFilePath = parsePath('restarter.json'); const configString = fs_1.default.readFileSync(configFilePath, { encoding: 'utf8' }); const configObj = JSON.parse(configString); return configObj; }; const main = () => { const targetScriptPath = parseTargetScriptPath(); let targetProcess = child_process_1.default.fork(targetScriptPath); console.log('Server started!'); const config = parseConfig(); const watchFiles = (config === null || config === void 0 ? void 0 : config.watch) || []; const handleFileChange = (filename) => { targetProcess.kill(); console.log(`${filename} changed!`); console.log('Server stopped!'); targetProcess = child_process_1.default.fork(targetScriptPath); console.log('Server restarted!'); }; const watchers = []; watchFiles.forEach((path) => { const isFile = /\.(ts|js)$/.test(path); const absolutePath = parsePath(path); if (isFile) { fs_1.default.watchFile(absolutePath, () => { handleFileChange(absolutePath); }); } else { const watcher = fs_1.default.watch(absolutePath, (event, filename) => { handleFileChange(filename); }); watchers.push(watcher); } }); process.on('SIGINT', () => { // exist target process targetProcess.kill(); // unwatch files watchFiles.forEach((path) => { const isFile = /\.(ts|js)$/.test(path); const absolutePath = parsePath(path); if (isFile) { fs_1.default.unwatchFile(absolutePath); } }); watchers.forEach(watcher => watcher.close()); // exit current process process.exit(); }); }; main();