I am trying to write an application that it will run as a Windows Service. For this, I have used the node-windows
package.
The application will print a simple message every second when started (at least for now) - used tasktimer
for defying the timer.
The problem that I found was that when the service is not installed, it will attempt to start the service and then install it (it works asynchronous). So I've tried to solve this problem using promisify
(to be able to use async - await
, but now it gives me the error: TypeError: Cannot read property 'svc' of undefined
...
This is the class that creates the service object and declares the methods:
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();
}
}
And this is the index.ts
file in which I call the class and try to do the logic:
1. run the install method (if it's already installed, just print a message and return; if not, install the service)
2. run the app (it will run infinitely)
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();
UPDATE: Ok, now I skipped the (un)install check, and it throws me the error:
TypeError: Cannot read property 'send' of null
at process.killkid (C:\Programs\node_modules\node-windows\lib\wrapper.js:177:11)
This makes the service to stop right after it's started. Any thoughts? :)