我正在尝试编写一个将作为 Windows 服务运行的应用程序。为此,我使用了该node-windows
软件包。该应用程序将在启动时(至少现在)每秒打印一条简单的消息 - 用于tasktimer
违抗计时器。我发现的问题是,当没有安装服务时,它会尝试启动服务然后安装它(它是异步工作的)。因此,我尝试使用promisify
( 能够使用async - await
,但现在它给了我错误:TypeError: Cannot read property 'svc' of undefined
...
这是创建服务对象并声明方法的类:
import * as pEvent from 'p-event'
var Service = require('node-windows').Service;
export class winServ {
svc = new Service({
name: 'Cli app',
description: 'Just a cli app...',
script: './src/index.js'
});
async alreadyInstalled() {
//check if service was already installed - return 0 or 1
this.svc.install();
await pEvent(this.svc, 'alreadyinstalled')
.then( () => {
console.log('Already installed!');
return 1;
});
return 0;
}
async installWinServ() {
this.svc.install();
await pEvent(this.svc, 'install')
.then( () => {
console.log('Service now installed!');
});
}
async uninstallWinServ() {
this.svc.uninstall();
// await pEvent(this.svc, 'alreadyuninstalled')
// .then( () => {
// console.log('Already uninstalled!');
// return;
// });
await pEvent(this.svc, 'uninstall')
.then( () => {
console.log('Uninstall complete.');
console.log('The service exists: ', this.svc.exists);
})
}
async runWinServ() {
console.log('Service has started!');
await this.svc.start();
}
async stopWinServ() {
await this.svc.stop();
}
}
这是index.ts
我调用类并尝试执行逻辑的文件:1.运行安装方法(如果已经安装,只需打印一条消息并返回;如果没有,安装服务)2.运行应用程序(它将无限运行)
import { winServ } from './windowsService/winServ';
var main = async () => {
try {
let serv = new winServ();
//let alreadyInstalled = await serv.alreadyInstalled();
//if (alreadyInstalled == 0) {
await serv.installWinServ();
//}
await serv.runWinServ();
let timer = new TaskTimer();
// define a timer that will run infinitely
timer.add(() => {
console.log("abcd");
timer.interval = 1000;
});
// start the timer
timer.start();
}
}
catch (err) {
console.log(err);
}
}
main();
更新:好的,现在我跳过了(卸载)安装检查,它向我抛出了错误:
TypeError: Cannot read property 'send' of null
at process.killkid (C:\Programs\node_modules\node-windows\lib\wrapper.js:177:11)
这使得服务在启动后立即停止。有什么想法吗?:)