UNPKG

orgdo

Version:

Command-line tool to manage the Todo lists

98 lines (97 loc) 3.54 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const ipc = require("node-ipc"); const cp = require("child_process"); const path = require("path"); const fs = require("fs"); const constants_1 = require("./constants"); ipc.config.appspace = constants_1.IPC_APP_SPACE; ipc.config.id = "client"; ipc.config.silent = true; class IPC { constructor(dataFile = constants_1.DATA_FILE) { this.dataFile = dataFile; } isRunning() { if (this.running) { return true; } let pid; try { pid = fs.readFileSync(constants_1.PID_FILE, "utf8"); } catch (err) { return false; } try { return process.kill(pid, 0); } catch (e) { return e.code === "EPERM"; } } exec(action, data) { return __awaiter(this, void 0, void 0, function* () { if (!this.isRunning()) { yield this.prepare(); } return new Promise((resolve, reject) => { ipc.connectTo(constants_1.IPC_SERVER_ID, () => { const server = ipc.of[constants_1.IPC_SERVER_ID]; server.on("error", err => { ipc.disconnect(constants_1.IPC_SERVER_ID); reject(err); }); server.on("connect", () => { server.emit(action, data); }); server.on("response", res => { ipc.disconnect(constants_1.IPC_SERVER_ID); resolve(res); }); }); }); }); } prepare() { return __awaiter(this, void 0, void 0, function* () { const ext = path.extname(__filename); const cmd = ext === ".ts" ? "ts-node" : "node"; cp.spawn(cmd, [path.resolve(__dirname, "server" + ext), this.dataFile], { detached: true, stdio: "ignore" }).unref(); yield ensureSpawnReady(); this.running = true; }); } } exports.default = IPC; function ensureSpawnReady(retry = 5) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { ipc.connectTo(constants_1.IPC_SERVER_ID, () => { const server = ipc.of[constants_1.IPC_SERVER_ID]; server.on("error", err => { retry--; if (retry === 0) { ipc.disconnect(constants_1.IPC_SERVER_ID); reject(err); } }); server.on("connect", () => { ipc.disconnect(constants_1.IPC_SERVER_ID); resolve(); }); }); }); }); }