Start nestjs project as a Windows service - node.js

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
Is there a way to use node-windows for a NestJS project?
Is it possible to use an absolute path with the nest cli start command? (e.g nest start --config ABSOLUTE_PATH)
How would you start an Angular project the same way?
Thank you.

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();

Related

Service not found after install service node-windows

My install service script as below:
install_windows_service.js
require("dotenv").config();
var Service = require("node-windows").Service;
// Create a new service object
var svc = new Service({
name: "STUtility",
description: "The web app with STUtility tools.",
script: process.env.WORKING_DIRECTORY + "index.js",
nodeOptions: ["--harmony", "--max_old_space_size=4096"],
workingDirectory: process.env.WORKING_DIRECTORY,
allowServiceLogon: true,
env: {
name: "NODE_ENV",
value: "production",
},
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on("install", function () {
svc.start();
console.log("install complete.");
console.log("The service exists: ", svc.exists);
});
// Just in case this file is run twice.
svc.on("alreadyinstalled", function () {
console.log("This service is already installed.");
});
// Listen for the "start" event and let us know when the
// process has actually started working.
svc.on("start", function () {
console.log(svc.name + " started!.");
});
svc.on("error", function () {
console.log("Something went wrong.");
});
svc.on("invalidinstallation ", function () {
console.log(" This service is detected but missing require files");
});
svc.install();
In terminal I run command:
node .\install_windows_service.js
Terminal show:
install complete. The service exists: true
But I cannot find out this service on Windows Services.

How to generate angular application using child_processes.spawn() method in a specific directory?

I have recently started to study about node and I wanted the node server should use:
ng new my-app
To create application without manually typing in the terminal.
I found that we could run command using child_processes.spawn() or child_processes.exec() in node.
I cannot understand why am i not able to do so with the below code?
spawn("ng",[join("ng new ", folderName," --directory ", workspaceName)]);
I am new to this topic so I would require your help to understand this.
Try This
var spawn = require('child_process').spawn;
var child = spawn('npm install -g #angular/cli && cd your directory && ng new my-dream-app', {
shell: true
});
child.stderr.on('data', function (data) {
console.error("STDERR:", data.toString());
});
child.stdout.on('data', function (data) {
console.log("STDOUT:", data.toString());
});
child.on('exit', function (exitCode) {
console.log("Child exited with code: " + exitCode);
});

Restarting nodejs server on crashing in an electronjs app

I am building an electron app and using nodejs as the backend server within the app.
How can I auto-restart the nodejs server if it encounters a crash?
I am currently using pm2 and using the following code in electron's main.js file
var pm2 = require("pm2");
pm2.connect(function(err) {
if (err) {
console.error(err);
process.exit(2);
}
pm2.start(
{
name: "mydesktopapp",
script: "./server/server.js", // nodejs Script to be run
exec_mode: "cluster",
instances: 1,
max_memory_restart: "5000M", // Optional: Restarts your app if it reaches 5GB
noDaemonMode: true,
watch: true
},
function(err, apps) {
pm2.disconnect(); // Disconnects from PM2
console.error(`Unable to start PM2: ${err}`);
if (err) throw err;
}
);
});
But this does not seem to work, as its throwing the following error:
Unable to start PM2: null
How do you guys handle this?
Thanks

Run npm install programmatically in specified folder

I want to run npm install via typescript code in a specified directory.
I found this code:
npm.load({}, function(err: any) {
// handle errors
// install module ffi
npm.commands.install(["hello-world#0.0.1"], function(err: any, data: any) {
// log errors or data
});
npm.on('log', function(message: any) {
// log installation progress
console.log(message);
});
});
But now I don't want to install hello-world, but just run npm install (without any package).
Additionally it should run in a path that I can specify, like ./folder/subfolder
How can I do that?
Apart from exec it's also possible to use the npm package:
import * as cp from 'child_process';
var npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
var path = '/path_to_npm_install';
const result = cp.spawnSync( npm, ['install'], {
cwd: path
});
If you're using Nodejs, which I think you are, you can run
child_process.exec('npm install') // or any other command which you give from terminal or command prompt
Check the documentation for child_process
https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
You can create a nodejs script that expect the directory path from user and create a child process and execute that command in that.
index.js
const { exec } = require('child_process');
exec(`cd /${process.env.PATH} | npm install`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
PATH=/path_of_directory_to_run_npm_install node index.js
Read more about child_process from nodejs documentation - https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

API HOST name from env variable node js

I have got a react app where I need to dynamically pass the API HOST name from environment (docker run --env API_HOST=localhost)
I'm using a child process in gulp to run 'node node.js'
//run npm install then node app
cp.spawn('npm install' ,{cwd:NODE_APP_FOLDER,env:process.env}, function(error, stdout, stderr) {
if (error) {
console.error(`exec error: ${error}`);
return;
}
var server = cp.spawn('node', ['app.js'], {
cwd: NODE_APP_FOLDER,
env: {
API_HOST:'localhost'
}
});
}
but in my code within the app process.env.API_HOST return undefined
Any help would be much appreciated

Resources