nkoniishvt
nkoniishvt

Reputation: 2521

Start nestjs project as a Windows service

We used to start Angular and NestJS (based on node.js) projects using Docker containers. This solution was discontinued for various reasons, so we are looking for a way to start these projects at the start of the PC (or on a trigger) and restart the project automatically if a crash occurs.

node-windows

This package builds a Windows service from a node.js project. NestJS being based on node.js, starting it using node.js is done this way (while in the project's folder):

node PATH_TO_PROJECT\node_modules\@nestjs\cli\bin\nest.js start --config .\tsconfig.build.json

The script used:

const svc = new Service({
  name: 'Test',
  description: 'Test',
    script:
      'PATH_TO_PROJECT\\node_modules\\@nestjs\\cli\\bin\\nest.js',
    scriptOptions: [
      'start --watch --config PATH_TO_PROJECT\\tsconfig.build.json',
    ],
  ],
  execPath: 'C:\\Program Files\\nodejs\\node.exe',
});

svc.on('install', function () {
  console.log('installed');
  svc.start();
});
svc.install();

The installation works as intended but in a browser, the server cannot be reached.

Questions

  1. Is there a way to use node-windows for a NestJS project?
  2. Is it possible to use an absolute path with the nest cli start command? (e.g nest start --config ABSOLUTE_PATH)
  3. How would you start an Angular project the same way?

Thank you.

Upvotes: 0

Views: 1433

Answers (1)

Phalapol Worakanyakul
Phalapol Worakanyakul

Reputation: 71

am use 'child_process' lib for run command like this

server.js

const { exec } = require("child_process");

exec("npm run start", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

and use node-windows like this

var Service = require('node-windows').Service;
var serviceDetail = require('./servicename')();

console.log(serviceDetail);
// Create a new service object
var svc = new Service({
  name: serviceDetail.name,
  description: serviceDetail.detail,
  script: './server.js'
});
console.log('start building up service name ' + serviceDetail.name);
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

Upvotes: 0

Related Questions