Giter VIP home page Giter VIP logo

node-windows's Introduction

node-windows

NPM version NGN Dependencies

This library can be used to install/start/stop/uninstall Node scripts as Windows background services for production environments. This is not a tool for developing applications, it is a tool for releasing them.

See node-mac and node-linux if you need to support those operating systems.

Tweet me (@goldglovecb) if you need me.

Sponsors


ย 

Can't sponsor?
Consider nominating @coreybutler for a Github star.

Overview

The following features are available in node-windows:

  • Service Management: Run Node.js scripts as native Windows services. Includes monitoring.
  • Event Logging: Create logs in the Event log.
  • Commands:
    • Elevated Permissions: Run a command with elevated privileges (may prompt user for acceptance)
    • Sudo: Run an exec command as a sudoer.
    • Identify Administrative Privileges: Determines whether the current user has administrative privileges.
    • List Tasks: A method to list running windows tasks/services.
    • Kill Task: A method to kill a specific windows service/task (by PID).

Installation

The recommended way to install node-windows is with npm, using the global flag:

npm install -g node-windows

Then, in your project root, run:

npm link node-windows

However; it is possible to use node-windows without the global flag (i.e. install directly into the project root). More details regarding why this is not the recommended approach are available throughout this Readme.

NO NATIVE MODULES

Using native node modules on Windows can suck. Most native modules are not distributed in a binary format. Instead, these modules rely on npm to build the project, utilizing node-gyp. This means developers need to have Visual Studio (and potentially other software) installed on the system, just to install a native module. This is portable, but painful... mostly because Visual Studio itself is over 2GB.

node-windows does not use native modules. There are some binary/exe utilities, but everything needed to run more complex tasks is packaged and distributed in a readily usable format. So, no need for Visual Studio... at least not for this module.


Windows Services

node-windows has a utility to run Node.js scripts as Windows services. Please note that like all Windows services, creating one requires administrative privileges. To create a service with node-windows, prepare a script like:

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

// Create a new service object
var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  nodeOptions: [
    '--harmony',
    '--max_old_space_size=4096'
  ]
  //, workingDirectory: '...'
  //, allowServiceLogon: true
});

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

svc.install();

The code above creates a new Service object, providing a pretty name and description. The script attribute identifies the Node.js script that should run as a service. Upon running this, the script will be visible from the Windows Services utility.

Windows Service

The Service object emits the following events:

  • install - Fired when the script is installed as a service.
  • alreadyinstalled - Fired if the script is already known to be a service.
  • invalidinstallation - Fired if an installation is detected but missing required files.
  • uninstall - Fired when an uninstallation is complete.
  • alreadyuninstalled - Fired when an uninstall is requested and no installation exists.
  • start - Fired when the new service is started.
  • stop - Fired when the service is stopped.
  • error - Fired in some instances when an error occurs.

In the example above, the script listens for the install event. Since this event is fired when a service installation is complete, it is safe to start the service.

Services created by node-windows are similar to most other services running on Windows. They can be started/stopped from the windows service utility, via NET START or NET STOP commands, or even managed using the sc utility.

Command-line Options

It may be desired to specify command-line switches to your script. You can do this by setting the scriptOptions within the service config:

var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  scriptOptions: '-c C:\\path\\to\\somewhere\\special -i'
});

Environment Variables

Sometimes you may want to provide a service with static data, passed in on creation of the service. You can do this by setting environment variables in the service config, as shown below:

var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  env: {
    name: "HOME",
    value: process.env["USERPROFILE"] // service is now able to access the user who created its' home directory
  }
});

You can also supply an array to set multiple environment variables:

var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  env: [{
    name: "HOME",
    value: process.env["USERPROFILE"] // service is now able to access the user who created its' home directory
  },
  {
    name: "TEMP",
    value: path.join(process.env["USERPROFILE"],"/temp") // use a temp directory in user's home directory
  }]
});

Node Executable Path

There are times when you may want to specify a specific node executable to use to run your script. You can do this by setting the execPath in the service config, as shown below:

var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  execPath: 'C:\\path\\to\\specific\\node.exe'
});

User Account Attributes

If you need to specify a specific user or particular credentials to manage a service, the following attributes may be helpful.

The user attribute is an object with three keys: domain,account, and password. This can be used to identify which user the service library should use to perform system commands. By default, the domain is set to the local computer name, but it can be overridden with an Active Directory or LDAP domain. For example:

app.js

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

// Create a new service object
var svc = new Service({
  name:'Hello World',
  script: require('path').join(__dirname,'helloworld.js'),
  //, allowServiceLogon: true 
});

svc.logOnAs.domain = 'mydomain.local';
svc.logOnAs.account = 'username';
svc.logOnAs.password = 'password';
...

Both the account and password must be explicitly defined if you want the service module to run commands as a specific user. By default, it will run using the user account that launched the process (i.e. who launched node app.js).

If you want to instruct winsw to allow service account logins, specify allowServiceLogon: true. This is disabled by default since some users have experienced issues running this without service logons.

The other attribute is sudo. This attribute has a single property called password. By supplying this, the service module will attempt to run commands using the user account that launched the process and the password for that account. This should only be used for accounts with administrative privileges.

app.js

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

// Create a new service object
var svc = new Service({
  name:'Hello World',
  script: require('path').join(__dirname,'helloworld.js')
});

svc.sudo.password = 'password';
...

Depending on other services

The service can also be made dependant on other Windows services.

var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  dependsOn: ["serviceA"]
});

Cleaning Up: Uninstall a Service

Uninstalling a previously created service is syntactically similar to installation.

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

// Create a new service object
var svc = new Service({
  name:'Hello World',
  script: require('path').join(__dirname,'helloworld.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();

The uninstall process only removes process-specific files. It does NOT delete your Node.js script!

What Makes node-windows Services Unique?

Lots of things!

Long Running Processes & Monitoring:

The built-in service recovery for Windows services is fairly limited and cannot easily be configured from code. Therefore, node-windows creates a wrapper around the Node.js script. This wrapper is responsible for restarting a failed service in an intelligent and configurable manner. For example, if your script crashes due to an unknown error, node-windows will attempt to restart it. By default, this occurs every second. However; if the script has a fatal flaw that makes it crash repeatedly, it adds unnecessary overhead to the system. node-windows handles this by increasing the time interval between restarts and capping the maximum number of restarts.

Smarter Restarts That Won't Pummel Your Server:

Using the default settings, node-windows adds 25% to the wait interval each time it needs to restart the script. With the default setting (1 second), the first restart attempt occurs after one second. The second occurs after 1.25 seconds. The third after 1.56 seconds (1.25 increased by 25%) and so on. Both the initial wait time and the growth rate are configuration options that can be passed to a new Service. For example:

var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  wait: 2,
  grow: .5
});

In this example, the wait period will start at 2 seconds and increase by 50%. So, the second attempt would be 3 seconds later while the fourth would be 4.5 seconds later.

Don't DOS Yourself!

Repetitive recycling could potentially go on forever with a bad script. To handle these situations, node-windows supports two kinds of caps. Using maxRetries will cap the maximum number of restart attempts. By default, this is unlimited. Setting it to 3 would tell the process to no longer restart a process after it has failed 3 times. Another option is maxRestarts, which caps the number of restarts attempted within 60 seconds. For example, if this is set to 3 (the default) and the process crashes/restarts repeatedly, node-windows will cease restart attempts after the 3rd cycle in a 60 second window. Both of these configuration options can be set, just like wait or grow.

Finally, an attribute called abortOnError can be set to true if you want your script to not restart at all when it exits with an error.

How Services Are Made

node-windows uses the winsw utility to create a unique .exe for each Node.js script deployed as a service. A directory called daemon is created and populated with myappname.exe and myappname.xml. The XML file is a configuration for the executable. Additionally, winsw will create some logs for itself in this directory (which are viewable in the Event log).

The myappname.exe file launches the node-windows wrapper, which is responsible for monitoring and managing the script. Since this file is a part of node-windows, moving the node-windows directory could result in the .exe file not being able to find the Node.js script. However; this should not be a problem if node-windows is installed globally, per the recommended installation instructions.

All of these daemon-specific files are created in a subdirectory called daemon, which is created in the same directory where the Node.js script is saved. Uninstalling a service will remove these files.

Event Logging

Services created with node-windows have two event logs that can be viewed through the Windows Event Viewer. A log source named myappname.exe provides basic logging for the executable file. It can be used to see when the entire service starts/stops or has errors. A second log, named after your service name (i.e. My App Name), is used by the node-windows monitor. It is possible to write to this log from the Node.js script using the node-windows Event Logging.


Event Logging

New as of v0.1.0 is a non-C++ based event logging utility. This utility can write to the event log, making your logs visible from the Event Viewer. It uses eventcreate under the hood.

To create a logger:

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

var log = new EventLogger('Hello World');

log.info('Basic information.');
log.warn('Watch out!');
log.error('Something went wrong.');

Looks similar to:

Event Logging in node-windows

Some lesser-used options are also available through node-windows event logging.

log.auditSuccess('AUser Login Success');
log.auditFailure('AUser Login Failure');

Each log type (info, warn, error, auditSuccess, and auditFailure) method optionally accepts two additional arguments, including a code and callback. By default, the event code is 1000 if not otherwise specified. To provide a custom event code with a log message and write that message to the console, the following code could be used:

Notice: It appears eventcreate only supports custom ID's <=1000.

log.info('Something different happened!', 700, function(){
  console.log('Something different happened!');
});

By default, event logs are all part of the APPLICATION scope. However; it is also possible to use the SYSTEM log. To do this, a configuration object must be passed to the new log:

var EventLogger = require('node-windows').EventLogger;
var log = new EventLogger({
  source: 'My Event Log',
  eventLog: 'SYSTEM'
});

Commands

node-windows ships with several commands to simplify tasks on MS Windows.

elevate

Elevate is similar to sudo on Linux/Mac. It attempts to elevate the privileges of the current user to a local administrator. Using this does not require a password, but it does require that the current user have administrative privileges. Without these privileges, the command will fail with a access denied error.

On systems with UAC enabled, this may prompt the user for permission to proceed:

UAC Prompt

Syntax:

elevate(cmd[,options,callback])

  • cmd: The command to execute with elevated privileges. This can be any string that would be typed at the command line.
  • options (optional): Any options that will be passed to require('child_process').exec(cmd,<OPTIONS>,callback).
  • callback (optional): The callback function passed to require('child_process').exec(cmd,options,<CALLBACK>).

sudo

Sudo acts similarly to sudo on Linux/Mac. Unlike elevate, it requires a password, but it will not prompt the user for permission to proceed. Like elevate, this still requires administrative privileges for the user, otherwise the command will fail. The primary difference between this and elevate() is the prompt.

Syntax:

sudo(cmd,password[,options,callback])

  • cmd: The command to execute with elevated privileges. This can be any string that would be typed at the command line.
  • password: The password of the user
  • options (optional): Any options that will be passed to require('child_process').exec(cmd,<OPTIONS>,callback).
  • callback (optional): The callback function passed to require('child_process').exec(cmd,options,<CALLBACK>).

isAdminUser

This asynchronous command determines whether the current user has administrative privileges. It passes a boolean value to the callback, returning true if the user is an administrator or false if it is not.

Example

var wincmd = require('node-windows');

wincmd.isAdminUser(function(isAdmin){
  if (isAdmin) {
    console.log('The user has administrative privileges.');
  } else {
    console.log('NOT AN ADMIN');
  }
});

list

The list method queries the operating system for a list of running processes.

var wincmd = require('node-windows');

wincmd.list(function(svc){
  console.log(svc);
},true);

This returns an array of running processes. Supplying the optional true argument in the above example provides a list with verbose output. The output is specific to the version of the operating system. Here is an example of verbose output on a Windows 8 computer.

[{
  ImageName: 'cmd.exe',
  PID: '12440',
  SessionName: 'Console',
  'Session#': '1',
  MemUsage: '1,736 K',
  Status: 'Unknown',
  UserName: 'Machine\\Corey',
  CPUTime: '0:00:00',
  WindowTitle: 'N/A'
},{
  ImageName: 'tasklist.exe',
  PID: '1652',
  SessionName: 'Console',
  'Session#': '1',
  MemUsage: '8,456 K',
  Status: 'Unknown',
  UserName: 'Machine\\Corey',
  CPUTime: '0:00:00',
  WindowTitle: 'N/A'
}]

The regular (non-verbose) output typically provides the ImageName,PID,SessionName, Session#, MemUsage, and CPUTime.

kill

This method will kill a process by PID.

var wincmd = require('node-windows');

wincmd.kill(12345,function(){
  console.log('Process Killed');
});

In this example, process ID 12345 would be killed. It is important to note that the user account executing this node script may require administrative privileges.

Troubleshooting

If you're experiencing issues with the examples, please review the TESTS.md file.

If you are encountering the invalidinstallation event, take a look at the daemon directory that is created during the installation to make sure the .exe and .xml files are there. In some circumstances, primarily during _un_installation, it is possbile for the process to temporarily lock a log file, which prevents Windows from removing it. In this scenario, simply run the uninstall again. In most cases this will fix the issue. If not, manually remove the daemon directory before running the installation again.

Thank You

There have been many contributors who have done everything from committing features to helping pick up slack while I've been swamped. I'm incredibly appreciative for the help.

Special thanks to @arthurblake whose modifications have FINALLY been added. Thanks to @hockeytim11, who helped compile and update a bunch of outstanding issues and started bringing support to the other node-* libraries.

Licenses

winsw and sudowin are the copyrights of their respective owners. winsw is distributed under an MIT license. sudowin is distributed under a BSD license.

All other scripts are Copyright (c) Corey Butler under an MIT license.

(The MIT License)

Copyright (c) 2013 Corey Butler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

node-windows's People

Contributors

adrai avatar aylusltd avatar carlosbello avatar coreybutler avatar countnazgul avatar cwalther avatar danielsantiago avatar demitchell14 avatar erik-krogh avatar etiktin avatar felipemsantana avatar fidgety avatar forty avatar frizzauk avatar gitter-badger avatar gm112 avatar hockeytim11 avatar j-oliveras avatar jpgrusling avatar lgruz avatar matthewadams avatar mdlawson avatar mrdnk avatar nabeards avatar pano9000 avatar phizaz avatar r1b avatar ratanaklun avatar snypelife avatar stormymcstorm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-windows's Issues

Stand-alone Service

I'm trying to look for a solution that can create a service for a node script and install it on any consumer computer.

So assuming the user doesn't have node.js installed on his/her machine. Can I still use this and run my script as a service?

ReferenceError when executing sudo

A spell problem on lib/binariesjs:75 ahs been found while trying to execute the service as sudo.

ReferenceError: otions is not defined
at Object.module.exports.sudo (W:\Marina\MarinaWebView\WebView\node_modules\node-windows\lib\binaries.js:75:20)

It looks like it only needs a variable rename 'otions' -> 'options'

Question: How to communicate with a service?

Say, I have a service that prints a message to the console every minute or so. How can I communicate with the service to change the message or make it reload its configuration file or something similar?

Windows Server 2008 R2 uninstall method permission denied

Hello,

first of all thank you very much for such a useful extension! The installation process works fine, but I receive an error during the uninstall process.
unbenannt
I am running the script having administration rights and every file except for the "nodejswrapperforsolr.exe" file is removed. I also do not know if it is caused by the error, but the actual windows service also remains in the list of all windows services. I believe, that it has something to do with my operating system (Windows Server 2008 R2), because only the executable file stays untouched and causes the permission error.

Thank you in advice,
vrugaiti

windows cannot find rmdir

I'm taking a copy of the example folder and running it verbatim (after fixing the require paths at the top). Installation works fine. After waiting a few minutes, the attempt to uninstall gives me a popup saying "windows cannot find rmdir." After I exit that popup, the console spits:

Uninstall complete.
The service exists:  true

And consequent attempts to install say:

This service is already installed.

Even though the files are being removed, the daemon directory remains, causing the glitch. If I remove the directory I am able to install again.

Service doesn't restart after error

I am using windows server 2012 and have successfully create and run the service.
When my node application exit with error (in this case, database has query error), the *.err.log file correspond correctly, however the service doesn't restart itself. the service status is still running and it never stop.

I have edit my service properties like this:
----Recovery tab
-first failure, second failure, subsequent failure with restart the service
-reset fail count after 1 day
-reset service after 1 minutes
-enable actions for stops with error.

----Log On tab
allow service to interact with desktop

I have also change the daemon/*.exe properties to run as administrator and checked the user privilege with isAdminUser() and it returns that the user has administrative privileges.

on the service object, i use this attributes :
wait: 1,
grow: .25

is there something I miss ?

execute command line code inside windows services

I want to execute "cmd" at the script (Ex: helloworled.js) inside windows services

cmd = path.join(__dirname,'sendInput.exe ') + input;
child = require('child_process').exec(cmd,
        function (error, stdout, stderr) {
            if (error !== null) {
                console.log('exec error: ' + error+'\n cmd: '+cmd);
                res.end("no");
            }else{
                console.log(input);
                res.end("ok");
            }

there is no error reporting but it is not executing the commend !!

event when i use "elevate" function like this

cmd = path.join(__dirname,'sendInput.exe ') + input;
child = require('node-windows').elevate(cmd,
        function (error, stdout, stderr) {
            if (error !== null) {
                console.log('exec error: ' + error+'\n cmd: '+cmd);
                res.end("no");
            }else{
                console.log(input);
                res.end("ok");
            }

the same issue

PS: tow above code snippets run correctly out of windows services

Running npm or coffee as command.

Hi there, this is a really cool package and I'd like to use it, BUT I have some issues. First is that the two ways I can start my node.js app are: coffee app.coffee and npm start. As far as I can tell neither of these is supported.

I understand the first is probably a little out of scope for this project but the second - running npm scripts would be useful.

Any chance of that making it in at some point?

Question: where does console.log go?

Sorry to write this here, but I can't find where else I should write this question...

I have a node express app that I have installed as a service using node-windows.
But I cannot find where the console.log messages are going. Note, they are NOT going into the event logging.

Strip color codes in logs

Use the following code from the stripcolors module to prevent strange output in logs.

.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, '')

Creating `winsw.exe.config` is required to run winws.exe under .NET 4.0 runtime

Is there any chance to put app.exe.config to daemon dir something like this?

var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js',
  supportedRuntime: ['v2.0.50727', 'v4.0]
});

or

svn.on('beforeInstall', function () {
    // creates .exe.config
});

https://github.com/kohsuke/winsw#net-runtime-40

Newer versions of Windows (confirmed on Windows Server 2012, possibly with Windows 8, too) do not ship with .NET runtime 2.0, which is what winsw.exe is built against. This is because unlike Java, where a newer runtime can host apps developed against earlier runtime, .NET apps need version specific runtimes.

One way to deal with this is to ensure that .NET 2.0 runtime is installed through your installer, but another way is to declare that winsw.exe can be hosted on .NET 4.0 runtime by creating an app config file winsw.exe.config.

<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
    <supportedRuntime version="v4.0" />
  </startup>
</configuration>

Logging Error

There is an issue with the logging and node 0.0.10 on 64-bit systems. The event logging module is being replaced with an alternative that does not require building a native module.

Events not getting logged within context of a service on Windows XP

For some reason, the script belowadds events to the event log under windows xp in a command prompt window but not when running as a service. The service executable seems to be able to write to the event log indicating stop/start of the service, just not the script.

I've tested this on Windows 7 and it works as expected.

var windows = require('node-windows');
var EventLogger = windows.EventLogger;
var eventLogger = new EventLogger({source: 'My Application'});
eventLogger.info('An Informational message');

var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end(JSON.stringify(process.env));
res.end('Hello World\n');
});

server.listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');

// Force the process to close after 15 seconds
/*setTimeout(function(){
process.exit();
},15000);
*/

Option to set Startup Type on Service Install?

As the title suggests, I'm looking for a way to set the service "Startup Type" option when I install my service.. Is that possible with this package?

I had a look at the functionality from winsw.exe and I don't see it there, but just to confirm... Would this sort of option rely on a feature from winsw, or am I missing something simple here?

clean shutdown

There does not seem to be an event/signaling method that can be used for the service script to know when to shutdown. Thus a clean shutdown is not possible.

Any thoughts ? Did I overlook anything ?

Uninstall directory

The install function has a dir parameter but unfortunately, the uninstall has not. So when you try to uninstall a service installed with a custom dir param, it says: Uninstall was skipped because process does not exist or could not be found.

I can submit a patch if you want.

Permission denied on Windows 7

There's an issue with the isAdminUser method that is preventing some users from ever receiving a true value, even when they are an admin. Issue is already fixed for the next release.

Service name : remove ".exe" extension ?

Hello,

When I create a service, when I check its properties, I can see Service name : followed by a name with a .exe extension.
Could you remove the .exe extension ?

I think that the problem is in lib/daemon.js near

 _xml: {
enumerable: false,
get: function(){
return require('./winsw').generateXml({
name: this.name,
id: this._exe,

the line id: this._exe should be replaced with something like id: this.name or something similar (I am not sure about this.name, so do not copy/paste my suggestion before thinking about the consequences on the service !)

Regards,
Yves

Feature Request: Restart on memory threshold.

Currently when an application running as a service runs out of memory the service does not restart, or show any sign of being stopped from the Windows Service Manager. It would be nice to be able to set a threshold on memory, where if reached the service would automatically restart.

Why daemon layer?

I'm using node-windows to register my nodejs application as service on win8. It works fine but I'm pretty curious that, why the launched "service" application have a daemon process?

I'm looking for a solution to have my app start on windows start, and restart when it crashed. So I register it as a service(using node-windows) but I find there're two nodejs launched: one daemon(wrapper.js), the other my app. Then I look into the source code and find that wrapper.js monitors my application.

So why node-windows don't have config to set up Recovery options of Windows service, but provide a daemon instead?

Error: Cannot find module 'node-windows'

Sorry, not sure if this a bug maybe more a question, apologies in advance. I followed the instructions for installing via npm, but when I try and run anything I just get the following error:

module.js:340
throw err;
^
Error: Cannot find module 'node-windows'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (F:\REngine\tools\node\services.js:1:76)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10

have also tried adding the path's to windows env. vars, adding the node-windows module to the project folder - same error? any help appreciated

Warning during call of "npm link node-windows"

I first did this:

npm install -g node-windows

And then I did this:

npm link node-windows

And received this warning:

npm WARN prefer global [email protected] should be installed with -g

Is it warning because it can't tell I installed 0.1.5 with -g? Or because there is actually a problem with how I installed it?

Helloworld example failure

Here is what I get when uninstalling the Helloworld example service...

D:\TekiaDev\Apps\TopicSpace\node_modules\node-windows\example>node uninstall

fs.js:760
return binding.unlink(pathModule._makeLong(path));
^
Error: EBUSY, resource busy or locked 'D:\TekiaDev\Apps\TopicSpace\node_modules\node-windows\example\d
aemon\helloworld.out.log'
at Object.fs.unlinkSync (fs.js:760:18)
at rm (D:\TekiaDev\Apps\TopicSpace\node_modules\node-windows\lib\daemon.js:458:22)
at D:\TekiaDev\Apps\TopicSpace\node_modules\node-windows\lib\daemon.js:467:15
at ChildProcess.exithandler (child_process.js:603:7)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:703:16)
at Socket. (child_process.js:916:11)
at Socket.EventEmitter.emit (events.js:95:17)
at Pipe.close (net.js:451:12)

The ./daemon/xml and ./daemon/wrapper get deleted ok however.

I get the same behavior with my service application.

Tks.

Can't tell if elevate was successful

If I use wincmd.elevate() and a UAC prompt pops up, there doesn't seem to be a way to tell if the user declined the granting of permission. In the callback, the error, stdout, and stderr arguments are all empty.

Elevate Process Exits Immediately

Normally, I might do something like this (using calc just for example):

require('child_process').exec('calc',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

This will open calc, and stdout and stderr will log after I close it, which allows me to check the output and respond when the user closes the child process. But when I use elevate:

require('node-windows').elevate('calc',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

Calc does indeed open with elevated privledges, but now stdout and stderr log immediately, I presume because it's aware of only the cmd or vbs, and not calc itself. This creates a problem, because now I can't check output or respond to the real close event.

I was hoping you had some thoughts to get around this issue.

EventLogger not picking up string argument

Specifying a string argument to EventLogger implicitly creates a config object as follows:
config = {name: }

However, when you initialize the logger's source property from the config object, you look for config.source. Consequently we always end up with 'Node.js' (the default) as the log source.

Tks!

Unlinking exe file fails on installation

I just noticed that the service uninstallation has trouble unlinking the exe file on my machine. This may be user error, in which case I apologize.

fs.js:760
  return binding.unlink(pathModule._makeLong(path));
                 ^
Error: EPERM, operation not permitted 'C:\Users\pschuegr\Documents\GitHub\wt\package\daemon\wt.exe'
    at Object.fs.unlinkSync (fs.js:760:18)
    at rm (C:\Users\pschuegr\AppData\Roaming\npm\node_modules\node-windows\lib\daemon.js:458:22)
    at C:\Users\pschuegr\AppData\Roaming\npm\node_modules\node-windows\lib\daemon.js:471:15
    at ChildProcess.exithandler (child_process.js:635:7)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:735:16)
    at Socket.<anonymous> (child_process.js:948:11)
    at Socket.EventEmitter.emit (events.js:95:17)
    at Pipe.close (net.js:466:12)
npm ERR! weird error 8
npm ERR! not ok code 0

The main executable is missing or cannot be found

Hello,

When I was trying to run the example code on my Windows 7 machine, I run into this error. I've spent some time trying to figure out the solution but no luck....

$node install

C:\myDirectory\node_modules\node-windows\lib\daemon.js:266
n<'The main executable is missing or cannot be found <`+path.join<me.root,this

TypeError: Cannot ready property 'root'of undefined
at Object.defineProperties.install.value [as install] <C:\myDirectory\node_modules\node-windows\lib\daemon.js:266:93>
at Object.

Question: Server restart - A way of starting the services, in a particular order?

This is a questions, rather than an issue.
I've only taken a look and done some basic stuff with it, but it looks great - thanks for your hardwork. Especially like the eventlogger.

The Questions

If the server has to restarted, is there a way of saying start this service first, then this one or these sets of services?

I'm thinking around, something like Seaport (by Substack), where I need to start the seaport server first, then any services that need to register with it.

It might be out of the scope of this module, but I'd be interested to hear your thoughts.

Node-schedule is not triggered.

I deployed my application as a service on Windows 8. The service was successfully deployed as localhost:8080 was up and running. In my app I have declared scheduled functions to run at specific times in day using node-schedule (https://www.npmjs.org/package/node-schedule). But these functions are not running at those times. For some reason, node-schedule function is not getting triggered. Here is my code:

var rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [new schedule.Range(0, 6)];
rule.hour = [new schedule.Range(10, 22)]
rule.minute = [30];

var j = schedule.scheduleJob(rule, function() {
//do something
}

I used the barebone service.js

wrapper restart feature not working

I could not get the service to restart at all when my process died (using the default options.) I tested this by having my server purposefully throw an unhandled exception (and also by calling process.exit.) after some interval.

It seems the monitor function (in wrapper.js) assumes that if the child process emits an exit event then the !child.pid is true. Testing and logging showed this not to be the case (I'm using latest node release 0.10.25).

I modified your code, changing the exit handler to set child to null and changed the test in the monitor function to if(!child || !child.pid) and that seemed to fix it.

Again I'm not submitting a pull request at this point as I'm still waiting for your new release. Perhaps this is something you've already addressed? Also it would be very nice to have the event log messages that are created around restarts show some detail on the try number and wait amount.

Unknown encoding error

When I try to run a basic service by using the same code from the demo:
var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'WeaveAgent',
  description: 'The nodejs.org example web server.',
  script: require('path').join(__dirname,'lib/weave-agent.js')
});

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

svc.install();

I get a weird 'unknown' encoding error':
screen shot 2013-07-23 at 3 09 50 pm

OS: Windows XP

Description not working

The description doesn't show in the windows Services pane.
OS: Win7
Node version: v0.10.20

Code

/*
 * Installs Resity application as a windows service
 */
var Service = require('node-windows').Service

/*
 * Create a new service object
 */
var svc = new Service({
     name:'todo'
  ,  description: 'Insert Description here'
  ,  script: process.cwd() + '/index.js'
})

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

svc.on ('uninstall', function () {
  console.log ('uninstalled')
  svc.install()
})

svc.on ('alreadyinstalled', function () {
  console.warn ('already installed')
  svc.uninstall()
})

svc.on ('invalidinstallation', function () {
  console.warn ('invalid installation')
})

svc.on ('start', function () {
  console.log ('service started')
})

svc.on ('stop', function () {
  console.log ('service stopped')
})

svc.on ('error', function (err) {
  console.error (err)
})

svc.install ()
// svc.uninstall ()

Services (screen-shot)
service

Simple example is not working on Win7

I'm using following code:

// file install-as-service.js
var Service = require('node-windows').Service;
var package = require('./package.json');
var name = package.name;
var description = package.description;
var svc = new Service({
  name: name,
  description: description,
  script: "" + __dirname + "/index.js"
});

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

svc.on('error', function() {
  return console.log('error');
});

svc.on('alreadyinstalled', function() {
  return console.log('alreadyinstalled');
});

svc.install();
// file index.js
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

But when called node install-as-service.js I've got following error:

buffer.js:434
      throw new Error('Unknown encoding');
            ^
Error: Unknown encoding
    at Buffer.toString (buffer.js:434:13)
    at Object.fs.readFileSync (fs.js:236:33)
    at Object.module.exports.createExe (D:\git\test-server\node_modules\node-windows\lib\winsw.js:93:19)
    at Object.defineProperties.install.value (D:\git\test-server\node_modules\node-windows\lib\daemon.js:284:19)
    at Object.oncomplete (fs.js:297:15)

And when called again, output was:

alreadyinstalled

I don't see any testserver.exe file created under ./daemon, only testserver.xml file is here.

I'm using node version 0.8.10 and Win7 Professional SP1.

Change service .exe publisher binary?

Service .EXE is compiled with a Publisher binary "CloudBees, Inc". How can I change it?
I checked js source code bit it seems I can't change it.. It looks as It is embedded into winsw.exe.

Thank you.

Node process is not terminated on service stop

When the service is stopped the wrapper process is detached and keeps running.
In my case the wrapper process spawns 2 child processes one node and one mongodb.
I have to terminate the process manually to restart the service.

I'm running windows 7 32 bits.

Event logging as non-admin?

Currently it looks like if I write to the event log, I get a UAC prompt with every message. Of course this doesn't happen if my program runs as an administrator, or, I presume, as a service.

Is there a way to write to the event log as a non-admin? It would be fine it UAC popped up the first time the log was created, but not with each entry.

no way to specify service logon info

Thanks for this elegant module. One thing that threw me while reading the doc is the user attribute. I assumed it was transferred over to the service logon information on the installed service, but it's not. Instead it's just the user account used to run the service setup command.

That being said, having the ability to programattically specify the service logon credentials is something I really need. Why not create another set of credentials in the config for that? It looks like it would be a quite simple modification, given that winsw supports this (under the serviceaccount xml attribute.)

One potential security issue is that the user account and password are placed in clear text in the xml file, so if this is done perhaps there would be a post install hook that munges the password in xml?

(P.S. Also, this is minor, but would be great if generateXml created xml that was formatted nicely for readability.)

Install Service not working on Windows 8.1 and .NET 4.5

I tried following script to run another node package as a service. Opened my nodejs commandprompt as administrator so I have the elevated rights. Nothing is happening. No Service running, no console output, no nothing. Let me know how I can get you more information.

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

// Create a new service object
var svc = new Service({
    name: 'Subway IRC',
    description: 'IRC client in the browser, running on port 3000',
    script: 'E:\\subway\\subway'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install', function() {
    console.log('Service "%s" installed', svc.name);
    svc.start();
    console.log('Service "%s" started', svc.name);
});

svc.install();

Unknown encoding

try run example on window 7 x86 non english localisation

buffer.js:440
throw new Error('Unknown encoding');
^
Error: Unknown encoding
at Buffer.toString (buffer.js:440:13)
at Object.fs.readFileSync (fs.js:236:33)
at Object.module.exports.createExe (c:\projects\example\node_modules\node-windows\lib\winsw.js:93:19)
at Object.defineProperties.install.value (c:\projects\example\node_modules\node-windows\lib\daemon.js:299:19)
at Object.oncomplete (fs.js:297:15)

Cannot find module node-windows

Windows server 2012, followed instructions installed node-windows globally. when I run my install script I get "cannot find module node-windows". I had to install it locally in the folder with my script to get it to work.

The installation and usage instructions might need to be updated or more testing done, something is awry.

NODE_ENV - how to set it?

Hi,

Great module, but how do I set f.ex. NODE_ENV=production?

Normally on windows you do it on the commandline with SET NODE_ENV=production, but I can not figure out how to do it with this module.

Thanks

EventLogger ignores source name defined in constructor

I'm using EventLogger for logging in my app, but all my logs have source set to "Node.js" instead of string which I defined in EventLogger constructor.

For example:
var EventLogger = require('node-windows').EventLogger;
var log = new EventLogger('TestLogger');
log.info('Test');

creates log in Windows Logs / Application with source "Node.js" instead of "TestLogger"

My Node.js version: 0.10.27,
OS: Windows 8.1 x64

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.