Node js как служба windows

It wasn’t my intention when I started the first article but this has become a series of how to run node applications in production with IIS on Windows. These are the previous articles on the topic:

  • Hosting a Node.js application on Windows with IIS as reverse proxy
  • Using HTTP platform handler to host a node.js application via IIS

In the last article a node web application was deployed on a Windows server. With the help of the HTTP platform handler, IIS manages the node process for us. When it receives a request it will start the node process and pass the web request for node to handle it.

In some cases however we don’t want to expose the node.js web application via IIS. I have built an internal API in the past which should not be accessible from the outside for security reasons. The internal API is only consumed by other applications running on the same server. In this case, we can’t rely on IIS to manage the node process for us as IIS would expose the web application to the internet.

We need an alternative to keep the node process running to make the internal API available on the server via localhost. PM2 can manage the node process and keep it up and running. Unfortunately I did not find a reliable way to start PM2 whenever the Windows Server restarts. Every time the server restarted, the internal API was down and had to be manually started.

Luckily there is a NPM package node-windows which can install a node application as a Windows service. This service can be automatically started when the server restarts.

This is the Hello World sample from the Express website, we will install it as a Windows service:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

Enter fullscreen mode

Exit fullscreen mode

The node-windows NPM package can do this for us. Run the following commands

npm install -g node-windows
npm link node-windows

Enter fullscreen mode

Exit fullscreen mode

Once the package is installed it can be used to install the application as a service with the following node script:

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

// Create a new service object
var svc = new Service({
  name:'Node application as Windows Service',
  description: 'Node application as Windows Service',
  script: 'C:\\temp\\test.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

Enter fullscreen mode

Exit fullscreen mode

Just run the script as any other node script:

node install-windows-service.js

Enter fullscreen mode

Exit fullscreen mode

If User Account Control (UAC) is enabled on Windows you will have to give permission a few times to complete the installation. Once this script has finished the service is installed and the application is running. You can find the service in the Services dialog. It will have the name that you have passed to the Service class in the node script.

Services dialog with the newly installed Windows service

If the service ever needs to be uninstalled, the Service class also has an uninstall method:

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

// Create a new service object
var svc = new Service({
  name:'Node application as Windows Service',
  description: 'Node application as Windows Service',
  script: 'C:\\temp\\test.js'
});

// Listen for the "uninstall" event so we know when it's done.
svc.on('uninstall',function(){
  console.log('Uninstall complete.');
  console.log('The service exists: ',svc.exists);
});

// Uninstall the service.
svc.uninstall();

Enter fullscreen mode

Exit fullscreen mode

This can also be run as any other node script:

node uninstall-windows.service.js

Enter fullscreen mode

Exit fullscreen mode

Because the Windows service is set to start automatic, it will start every time the server is restarted. Exactly as expected. Happy deploying!

This is a cross post from my own blog.

  • Home
  • Products
  • AlwaysUp
  • Applications
  • Node.js

How to Run Any Node.js Application as a Windows Service with AlwaysUp

Start your Node.js script when your PC boots and keep it running 24/7 in the background. No need to log in!

Node.js is a platform for building scalable, server-side Javascript applications.

AlwaysUp includes advanced tools to make Node.js start at boot and run 24/7.

The Application Advisor will help you install Node.js as a Windows Service with all our recommended settings — in just a few clicks. Simply select Advisor from the Application menu and follow the straightforward prompts.

To configure your Node.js script as a Windows Service with AlwaysUp 8.0 and later:

  1. Download and install and configure Node.js, if necessary.

  2. Download and install AlwaysUp, if necessary.

  3. Start AlwaysUp.

  4. Select Application > Add to open the Add Application window:

    Add Application

  5. On the General tab:

    • In the Application field, enter the full path to the Node.js executable, node.exe.
      By default, this will be:

      C:\Program Files\nodejs\node.exe

    • In the Arguments field, enter the full path to your Node.js script, enclosing the entire thing in quotes if it has a space.
      We have specified our slightly modified version of the sample web server script mentioned on the Node.js home page,
      saved as C:\Scripts\web-server.js.

    • In the Name field, enter the name that you will call the application in AlwaysUp.
      We have specified Node.js Server but you can specify another name if you like.

    Node.js Windows Service: General Tab

  6. Click over to the Startup tab and check the Ensure that the Windows Networking components have started box.
    This informs AlwaysUp that Node.js needs TCP/IP networking support to do its work.

    Node.js Windows Service: Startup Tab

  7. Click the Save >> button. In a couple of seconds, an application called Node.js Server will show up in the AlwaysUp window.
    It is not yet running though.

    Node.js Windows Service: Created

  8. To start your application from AlwaysUp, choose Application > Start «Node.js Server»:

    Node.js Windows Service: Running

    Note that Node.js will be running in Session 0. If you are on Windows 2012/8/7/2008/Vista, you can select Tools > Switch to Session 0… to see the usual console window running in the
    isolated Session 0:

    Node.js Windows Service: Running in Session 0

  9. That’s it! Next time your computer boots, your Node.js application will start up immediately, before anyone logs on.
    We encourage you to edit your application in AlwaysUp and check out the many other settings that may be appropriate for your environment.
    For example, send email alerts if the application stops, boost its priority, etc.


Node.js not working properly as a Windows Service?

  • From AlwaysUp, select Application > Report Activity > Today… to bring up a HTML report detailing the interaction between AlwaysUp and your application.
    The AlwaysUp Event Log Messages page explains the more obscure messages.
  • Consult the AlwaysUp FAQ for answers to commonly asked questions and troubleshooting tips.
  • Contact us and we will be happy to help!

In a development environment, it’s very easy to run your server using a simple command but in a production environment, your Node application needs to be up and running at all times.

To run a Node application as a Windows service, you need to leverage another third-party tool. The best and the easiest one to configure in this case would be NSSM.

What does NSSM offer?

Once you install and configure NSSM for your Node.js application, you can be assured that your server will run forever as a background service.

Here are the most salient features of NSSM:

  • NSSM is a free and open source software
  • It converts executables into Windows services
  • NSSM can manage the CPU affinity and process priority of the managed application
  • It acts as a Load balancer for your services
  • NSSM monitors the services at all times. Whenever there’s a failure or machine reboots, it will automatically start the services

How to run Node server as a Service using NSSM

Here are step-by-step instructions with screenshots on how to install and use NSSM to ensure the availability of your Node application server at all times:

Step-1: Download NSSM

You can download the latest package of NSSM from HERE.

If you’re running Windows 10, you should download the latest pre-release build to avoid any problems.

NSSM download

Step-2: Renaming and placing the NSSM folder in C: drive

It’s not a compulsory step but it’s better to rename the folder to a simple name and place it in the C: drive for better accessibility.

For this exercise we are going to name the folder “nssm” and move it to the main C: drive.

NSSM placement

Step-3: Creating a Service for your Nodejs Application

The next step is to create a Windows service using NSSM for your Node application. Follow the procedure step-by-step and make sure to get the locations of the folders right.

  1. Open the command prompt and make sure to run as Administrator.
  2. Traverse to the path where nssm.exe is located. If you followed the previous step it should be located in C:\nssm\nssm\win64 (If your Windows is 4-bit).
    NSSM Location

  3. Assuming you have Nodejs installed in the default folder (C:\Program Files\nodejs), you need to enter the following command in the command prompt: (app is the service name that you want to assign for your Node application)
    NSSM install

  4. Now we need to set the App Directory for the Nodejs app that you need to run as service. Assuming the App is located at: D:\app Enter this command:
    NSSM App directory

  5. Once that’s done, you need to set the App parameters to the server.js file that needs to run every time. Here’s the command to do that:
    NSSM App Parameters

  6. Now finally, you can initiate the new service with the command:
    NSSM start app

And that is it! Your Nodejs app will now run as a background Windows service. If anything fails or your machine boots up, the application will launch automatically, ensuring maximum availability for your Node application.

Additional Resources

  • How to run any Application as a Windows Service (Step-by-step)

In a recent project we are using websockets to respond in Apex to certain database events.

The websocket server is based upon node.js. One of the tasks was to setup this server as an service under a normal Windows Server 2003 (yes I know it is old) infrastructure. This post describes the steps how to setup such a service and also includes some monitoring information.

The prerequisties are that you already need to have node installed on your machine.

To start the websocket server we would usually call

node synwsserver.js

This starts the server. All the output (console.log) will be written to the terminal.

But we don’t want to run it manually each time. Instead we would like to setup it as a windows service. So here is how to achieve that. The same logic can be applied for any node module, not just for websockets.

1) Load node-windows

The node package that I used is node-windows. It is very lightweight and did not have dependencies to node-gyp which often gives trouble.

The command to install it is:

npm install node-windows

The author recommends to install it using the global flag -g. You might want to consider it. I did not encounter issues without the global flag.

2) Install the service

In the node “shell” run the following commands.
The script name is the same script that would be called directly from node.

File: installServiceApexWS.js
var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'syn-apex-websocket',
  description: 'The websocket server for the APEX project.',
  script: 'D:\\tomcat\\nodejs\\synwsserver.js'
});

// Listen for the 'install' event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

// install the service
svc.install();

The name and the description can then be seen in the windows service tool.

Result

ws_service

And we are able to start and stop the service.

Problem solved!

Ok there is a tiny bit more. We want to be able to uninstall it as well. And we need to think about the messages that were previously written to the console.

Run in Batch

The sequence of javascript commands can also be put into a .BAT file. I choose to separate the batch call from the js code, so there are two files now.

File: installServiceApexWS.bat
echo "Installing service..."
start "install service - Syntegris APEX websocket server" node installServiceApexWS.js
echo "Service installiert."
exit;

3) Uninstall the service

The logic to deinstall the service is very similar to installing it.

File: uninstallServiceApexWS.js
var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'syn-apex-websocket',
  description: 'The websocket server for the APEX project.',
  script: 'D:\\tomcat\\nodejs\\synwsserver.js'
});

// Listen for the 'uninstall' event so we know when it is done.
svc.on('uninstall',function(){
  console.log('Uninstall complete.');
  console.log('The service exists: ',svc.exists);

});

// Uninstall the service.
svc.uninstall();

File: uninstallServiceApexWS.bat
echo "Uninstalling service..."
start "uninstall service - Syntegris APEX websocket server"  node uninstallServiceApexWS.js
echo "Service deinstalliert."
exit;

4) Add event logging

Node-windows comes with same basic windows event logging. That means certain type of actions can be written into the default windows eventlog.

An example

/*
  add logging for Windows events
*/
var EventLogger = require('node-windows').EventLogger;
var log = new EventLogger('syn-apex-websocket');

...

/* Start listening on the configured port and write to standard output*/
server.listen(config.port, function() {
    console.log((new Date()) + ' Server is listening on port ' + config.port);
    log.info('Server is listening on port ' + config.port);

});

An this is how the result looks like in the Event Viewer (search for Event on your Windows Server) to find the tool.

ws_service_eventviewer

Приветствую всех резидентов хабра и читающих его.

В этой короткой статье описываются два способа запуска приложений node.js, как сервисов Windows, используя nssm.

Установка

$ npm install winser

Аргументы:
-h, —help — вывод справки
-V, —version — вывод номера версии
-i, —install — установка приложения как сервиса Windows
-r, —remove — удаление сервиса Windows для приложения
-x, —stop — останов сервиса перед удалением
-s, —silent — подавление вывода сообщений на консоль
-c, —confirmation — запрос подтверждения перед установкой/удалением
-p, —path [path] — путь до приложения, устанавливаемого как сервис [текущая директория]

Вариант 1
Удобный способ, используя пакет package.json:

«scripts»: {
«postinstall»: «winser -i -s -c»,
«preuninstall»: «winser -r -x -s»,
}

Теперь, для установки приложения на сервере, надо выполнить:

npm install git://github.com/myprivate/repository/url.git

Аргументы послеустановочного (postinstall) скрипта:
i install — установка
s silent — подавление вывода
c confirmation — запрос подтверждения. Очень удобная опция, т.к. во время разработки нет необходимости устанавливать приложение, как сервис Windows, но часто выполняя команду «npm install» в папке, вы всегда сможете это отменить, выбрав ‘n’.

Аргументы скрипта перед удалением (preuninstall):

x — останов сервиса перед удалением
r — удаление сервиса
s — подавление вывода

Вариант 2
Добавьте два следующих скрипта в пакет package.json:

«scripts»: {
«install-windows-service»: «winser -i»,
«uninstall-windows-service»: «winser -r»
}

Теперь вы можете установить сервис, выполнив:
npm run-script install-windows-service

Как это работает
Когда вы устанавливаете ваше node.js приложение, как сервис Windows, то оно регистрируется, используя nssm.exe (находящийся в папке модуля). Запустив сервис nssm.exe, он, в свою очередь, выполнит запуск («npm start») вашего приложения.
Помните, что по умолчанию при запуске npm, указано «node server.js».
Имя сервиса будет аналогичным опции «name» из пакета package.json.

Скачать:
Скачать zip
Скачать tar.gz
Ссылка на github

Ссылки:
Node.js on windows by Tatham Oddie
nssm

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Kmsauto активатор windows 10 отзывы
  • Как восстановить все настройки windows 10 по умолчанию
  • Redmi airdots 2 драйвер windows 7
  • Windows arm запуск x86 приложений
  • Что лучше по производительности windows 10 или windows 11