How to host a Node.Js application in shared hosting [closed] - node.js

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
How to host a Node.Js application in a shared hosting
I want to host a node.js application in shared hosting. Does anyone have any reference or documentation to refer to?

You can run node.js server on a typical shared hosting with Linux, Apache and PHP (LAMP). I have successfully installed it, even with NPM, Express and Grunt working fine. Follow the steps:
1) Create a new PHP file on the server with the following code and run it:
<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');
2) The same way install your node app, e.g. jt-js-sample, using npm:
<?php
exec('node/bin/npm install jt-js-sample');
3) Run the node app from PHP:
<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=49999 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:49999/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
//If couldn't connect, try increasing usleep
echo 'Error: ' . curl_error($curl);
} else {
//Split response headers and body
list($head, $body) = explode("\r\n\r\n", $resp, 2);
$headarr = explode("\n", $head);
//Print headers
foreach($headarr as $headval) {
header($headval);
}
//Print body
echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);
Voila! Have a look at the demo of a node app on PHP shared hosting.
EDIT: I started a Node.php project on GitHub.

Connect with SSH and follow these instructions to install Node on a shared hosting
In short you first install NVM, then you install the Node version of your choice with NVM.
wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash
Your restart your shell (close and reopen your sessions). Then you
nvm install stable
to install the latest stable version for example. You can install any version of your choice. Check node --version for the node version you are currently using and nvm list to see what you've installed.
In bonus you can switch version very easily (nvm use <version>)
There's no need of PHP or whichever tricky workaround if you have SSH.

I installed Node.js on bluehost.com (a shared server) using:
wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node
This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.
then
./node/bin/npm install jt-js-sample
Returns:
npm WARN engine jt-js-sample#0.2.4: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
jt-js-sample#0.2.4 node_modules/jt-js-sample
└── express#4.12.4 (merge-descriptors#1.0.0, utils-merge#1.0.0, cookie-signature#1.0.6, methods#1.1.1, cookie#0.1.2, fresh#0.2.4, escape-html#1.0.1, range-parser#1.0.2, finalhandler#0.3.6, content-type#1.0.1, vary#1.0.0, parseurl#1.3.0, serve-static#1.9.3, content-disposition#0.5.0, path-to-regexp#0.1.3, depd#1.0.1, qs#2.4.2, on-finished#2.2.1, debug#2.2.0, etag#1.6.0, proxy-addr#1.0.8, send#0.12.3, type-is#1.6.2, accepts#1.2.7)
I can now use the commands:
# ~/node/bin/node -v
v0.12.4
# ~/node/bin/npm -v
2.10.1
For security reasons, I have renamed my node directory to something else.

A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.
Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.
See a2hosting.com.

You should look for a hosting company that provides such feature, but standard simple static+PHP+MySQL hosting won't let you use node.js.
You need either find a hosting designed for node.js or buy a Virtual Private Server and install it yourself.

Related

ASP.NET Core NodeServices on Azure Linux WebApp

I am used to publish Azure WebApps on Windows but now I am trying to deploy an ASP.NET Core 3 (with NodeServices) to a Linux WebApp and I am receiving the following error message:
InvalidOperationException: Failed to start Node process. To resolve this:.
[1] Ensure that Node.js is installed and can be found in one of the PATH directories.
Current PATH enviroment variable is: /opt/dotnetcore-tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/site/wwwroot
Make sure the Node executable is in one of those directories, or update your PATH.
On Windows WebApps I have a lot of other apps and all are fine.
On Kudu I typed node -v and the output was v12.13.0.
Can anybody please help me?
Thank you very much.
After a long research and the assistance of Microsoft's Engineer https://github.com/caroe2014 this is the three steps final answer:
1) Startup.cs
services.AddNodeServices(options =>
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
options.ProjectPath = Path.GetFullPath("/home/site/wwwroot");
}
}
);
2) And what I found is Node is not present in the container so it is necessary to have a script to install and start it before starting the app itself. So I have this start1.cs file:
#!/bin/bash
apt-get install curl
curl -sL https://deb.nodesource.com/setup_12.x | bash
apt-get install -y nodejs
set -e
export PORT=8080
export ASPNETCORE_URLS=http://*:$PORT
dotnet "Web.Identity.dll"
Where Web.Identity.dll is the dll of my app.
3) Set startup command to /home/site/wwwroot/start1.sh (On Azure Portal - App service Configuration - or Azure DevOps).
That's all.
Try to mention the path in the code, This is how NodeServices was configured in Startup.cs:
services.AddNodeServices(options =>
{
options.ProjectPath = "Path\That\Doesnt\Exist";
});

NPM package `pem` doesn't seem to work in AWS lambda NodeJS 10.x (results in OpenSSL error)

When I run the function locally on NodeJS 11.7.0 it works, when I run it in AWS Lambda NodeJS 8.10 it works, but I've recently tried to run it in AWS Lambda NodeJS 10.x and get this response and this error in Cloud Watch.
Any thoughts on how to correct this?
Response
{
"success": false,
"error": "Error: Could not find openssl on your system on this path: openssl"
}
Cloudwatch Error
ERROR (node:8) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
Function
...
const util = require('util');
const pem = require('pem');
...
return new Promise((fulfill) => {
require('./certs').get(req, res, () => {
return fulfill();
});
}).then(() => {
const createCSR = util.promisify(pem.createCSR);
//This seems to be where the issue is coming from
return createCSR({
keyBitsize: 1024,
hash: HASH,
commonName: id.toString(),
country: 'US',
state: 'Maryland',
organization: 'ABC', //Obfuscated
organizationUnit: 'XYZ', //Obfuscated
});
}).then(({ csr, clientKey }) => {
...
}).then(async ({ certificate, clientKey }) => {
...
}, (err) => {
return res.status(404).json({
success: false,
error: err,
});
});
...
I've tried with
"pem": "^1.14.3", and "pem": "^1.14.2",
I tried the answer documented by #Kris White, but I was not able to get it to work. Each execution resulted in the error Could not find openssl on your system on this path: /opt/openssl. I tried several different paths and approaches, but none worked well. It's entirely possible that I simply didn't copy the OpenSSL executable correctly.
Since I needed a working solution, I used the answer provided by #Wilfred Dittmer. I modified it slightly since I wasn't using Docker. I launched an Amazon Linux 2 server, built OpenSSL on it, transferred the package to my local machine, and deployed it via Serverless.
Create a file named create-openssl-zip.sh with the following contents. The script will create the Lambda Layer OpenSSL package.
#!/bin/bash -x
# This file should be copied to and run inside the /tmp folder
yum update -y
yum install autoconf bison gcc gcc-c++ libcurl-devel libxml2-devel -y
curl -sL http://www.openssl.org/source/openssl-1.1.1d.tar.gz | tar -xvz
cd openssl-1.1.1d
./config --prefix=/tmp/nodejs/openssl --openssldir=/tmp/nodejs/openssl && make && make install
cd /tmp
rm -rf nodejs/openssl/share nodejs/openssl/include
zip -r lambda-layer-openssl.zip nodejs
rm -rf nodejs openssl-1.1.1d
Then, follow these steps:
Open a terminal session in this project's root folder.
Run the following command to upload the Linux bash script.
curl -F "file=#create-openssl-zip.sh" https://file.io
Note: The command above uses the popular tool File.io to copy the script to the cloud temporarily so it can be securely retrieved from the build server.
Note: If curl is not installed on your dev machine, you can also upload the script manually using the File.io website.
Copy the URL for the uploaded file from either the terminal session or the File.io website.
Note: The url will look similar to this example: https://file.io/a1B2c3
Open the AWS Console to the EC2 Instances list.
Launch a new instance with these attributes:
AMI: Amazon Linux 2 AMI (HVM), SSD Volume Type (id: ami-0a887e401f7654935)
Instance Type: t2.micro
Instance Details: (use all defaults)
Storage: (use all defaults)
Tags: Name - 'build-lambda-layer-openssl'
Security Group: 'Create new security group' (use all defaults to ensure Instance will be publicly accessible via SSH over the internet)
When launching the instance and selecting a key pair, be sure to choose a Key Pair from the list to which you have access.
Launch the instance and wait for it to be accessible.
Once the instance is running, use an SSH Client to connect to the instance.
More details on how to open an SSH connection can be found here.
In the SSH terminal session, navigate to the tmp directory by running cd /tmp.
Download the bash script uploaded earlier by running curl {FILE_IO_URL} --output create-openssl-zip.sh.
Note: In the script above, replace FILE_IO_URL with the URL returned from File.io and copied in step 3.
Execute the bash script by running sudo bash ./create-openssl-zip.sh. The script may take a while to complete. You may need to confirm one or more package install prompts.
When the script completes, run the following command to upload the package to File.io: curl -F "file=#lambda-layer-openssl.zip" https://file.io.
Copy the URL for the uploaded file from the terminal session.
In the terminal session on the local development machine, run the following command to download the file: curl {FILE_IO_URL} --output lambda-layer-openssl.zip.
Note: In the script above, replace FILE_IO_URL with the URL returned from File.io and copied in step 13.
Note: If curl is not installed on your dev machine, you can also download the file manually by pasting the copied URL in the address bar of your favorite browser.
Close the SSH session.
In the EC2 Instances list, terminate the build-lambda-layer-openssl EC2 instance since it is not needed any longer.
The OpenSSL Lambda Layer is now ready to be deployed.
For completeness, here is a portion of my serverless.yml file:
functions:
functionName:
# ...
layers:
- { Ref: OpensslLambdaLayer }
layers:
openssl:
name: ${self:provider.stage}-openssl
description: Contains openssl command line utility for lambdas that need it
package:
artifact: 'path\to\lambda-layer-openssl.zip'
compatibleRuntimes:
- nodejs10.x
- nodejs12.x
retain: false
...and here is how I configured PEM in the code file:
import * as pem from 'pem';
process.env.LD_LIBRARY_PATH = '/opt/nodejs/openssl/lib';
pem.config({
pathOpenSSL: '/opt/nodejs/openssl/bin/openssl',
});
// other code...
I contacted AWS Support about this and it turns out that the openssl library is still on the Node10x image, just not the command line utility. However, it's pretty easy to just grab it off a standard AMI and use it as a Lambda layer.
Steps:
Launch an Amazon Linux 2 AMI as an EC2
SSH into the box, or use an SFTP utility to connect to the box
Copy the command line utility for openssl at /usr/bin/openssl somewhere you can work with it locally. In my case I downloaded it to my Mac even though it is a Linux file.
Verify that it's still marked as executable (chmod a+x openssl if necessary if you've downloaded it elsewhere)
Zip up the file
Optional: Upload it to an S3 bucket you can get to
Go to Lambda Layers in the AWS console
Create a new lambda layer. I named mine openssl and used the S3 pointer to the file on S3. You can also upload the zip directly if you have it on a local file system.
Attach the arn provided for the layer to your Lambda function. I use serverless so it was defined in the function setup per their documentation.
In your code, reference openssl as /opt/openssl or you can avoid pathing it in your code (or may not have an option if it's a package you don't control) by adding /opt to you path, i.e.
process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'] + ':/opt';
The layer will have been unzipped for you and because you set it to be executable beforehand, it should just work. The underlying openssl libraries are there, so just copying the cli works just fine.
What you can do is to create a lambda layer with the openssl library.
Using the lambdaci/lambda:build-nodejs10.x you can compile the openssl library and create a zip file from the install. The zip file you can then use as a layer for your lambda.
Create a file called create-openssl-zip.sh and make sure to chmod u+x it.
#!/bin/bash -x
# This file should be run inside the lambci/lambda:build-nodejs10.x container
yum update -y
yum install autoconf bison gcc gcc-c++ libcurl-devel libxml2-devel -y
curl -sL http://www.openssl.org/source/openssl-1.1.1d.tar.gz | tar -xvz
cd openssl-1.1.1d
./config --prefix=/var/task/nodejs/openssl --openssldir=/var/task/nodejs/openssl && make && make install
cd /var/task/
rm -rf nodejs/openssl/share
rm -rf nodejs/openssl/include
zip -r lambda-openssl-layer.zip nodejs
cp lambda-openssl-layer.zip /opt/layer/
Then run:
docker run -it -v `pwd`:/opt/layer lambci/lambda:build-nodejs10.x /opt/layer/create-openssl-zip.sh
This will run the script inside the docker container and when it is done you have a file called lambda-openssl-layer.zip in your current directory.
Upload this lambda to an s3 bucket and create a lambda layer.
On your original lambda, add this layer and modify your code so that the PEM library knows where to look for the OpenSSL library as follows:
PEM.config({
pathOpenSSL: '/opt/nodejs/openssl/bin/openssl'
})
And finally add an extra environment variable to your lambda called LD_LIBRARY_PATH with value /opt/nodejs/openssl/lib
Otherwise it will fail with:
/opt/nodejs/openssl/bin/openssl: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory
PEM NPM docs says:
Setting openssl location
In some systems the openssl executable might not be available by the default name or it is not included in $PATH. In this case you can define the location of the executable yourself as a one time action after you have loaded the pem module:
So I think it is not able to find OpenSSL path in system you can try configuring it programmatically :
var pem = require('pem')
pem.config({
pathOpenSSL: '/usr/local/bin/openssl'
})
As you are using AWS Lambda so just try printing process.env.path you will get idea of whether OpenSSL is included in path env variable or not.
You can also check 'OpenSSL' by running below code
const exec = require('child_process').exec;
exec('which openssl',function(err,stdopt,stderr){
console.log(err ? err : stdopt);
})
UPDATE
As #hoangdv mentioned in his answer openssl is seems to be removed for node10.x runtime and I think he is right. Also, we have read-only access to file system so we can't do much.
#Seth McClaine, you can give try for node-forge npm module. One of the module built on top of this is 'https://github.com/jfromaniello/selfsigned' which will make your task easier
https://github.com/lambci/git-lambda-layer/issues/13#issue-444697784 (announcement email)
It seem openssl has been removed in nodejs10.x runtime.
I have checked again on lambci/lambda:build-nodejs10.x docker image and confirmed that. Maybe, you need to change your runtime version or find another way to createCSR.
which: no openssl in (/var/lang/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin)

how to run windows service automatically using nodejs application? [duplicate]

Can any node.js experts tell me how I might configure node JS to autostart a server when my machine boots?
I'm on Windows
This isn't something to configure in node.js at all, this is purely OS responsibility (Windows in your case). The most reliable way to achieve this is through a Windows Service.
There's this super easy module that installs a node script as a windows service, it's called node-windows (npm, github, documentation). I've used before and worked like a charm.
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'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
p.s.
I found the thing so useful that I built an even easier to use wrapper around it (npm, github).
Installing it:
npm install -g qckwinsvc
Installing your service:
> qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed
Uninstalling your service:
> qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled
If you are using Linux, macOS or Windows pm2 is your friend. It's a process manager that handle clusters very well.
You install it:
npm install -g pm2
Start a cluster of, for example, 3 processes:
pm2 start app.js -i 3
And make pm2 starts them at boot:
pm2 startup
It has an API, an even a monitor interface:
Go to github and read the instructions. It's easy to use and very handy. Best thing ever since forever.
If I'm not wrong, you can start your application using command line and thus also using a batch file. In that case it is not a very hard task to start it with Windows login.
You just create a batch file with the following content:
node C:\myapp.js
and save it with .bat extention. Here myapp.js is your app, which in this example is located in C: drive (spcify the path).
Now you can just throw the batch file in your startup folder which is located at C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Just open it using %appdata% in run dailog box and locate to >Roaming>Microsoft>Windows>Start Menu>Programs>Startup
The batch file will be executed at login time and start your node application from cmd.
This can easily be done manually with the Windows Task Scheduler.
First, install forever.
Then, create a batch file that contains the following:
cd C:\path\to\project\root
call C:\Users\Username\AppData\Roaming\npm\forever.cmd start server.js
exit 0
Lastly, create a scheduled task that runs when you log on. This task should call the batch file.
I would recommend installing your node.js app as a Windows service, and then set the service to run at startup. That should make it a bit easier to control the startup action by using the Windows Services snapin rather than having to add or remove batch files in the Startup folder.
Another service-related question in Stackoverflow provided a couple of (apprently) really good options. Check out How to install node.js as a Windows Service. node-windows looks really promising to me. As an aside, I used similar tools for Java apps that needed to run as services. It made my life a whole lot easier. Hope this helps.
you should try this
npm forever
https://www.npmjs.com/package/forever
Use pm2 to start and run your nodejs processes on windows.
Be sure to read this github discussion of how to set up task scheduler to start pm2: https://github.com/Unitech/pm2/issues/1079
Here is another solution I wrote in C# to auto startup native node server or pm2 server on Windows.
I know there are multiple ways to achieve this as per solutions shared above. I haven't tried all of them but some third party services lack clarity around what are all tasks being run in the background. I have achieved this through a powershell script similar to the one mentioned as windows batch file. I have scheduled it using Windows Tasks Scheduler to run every minute. This has been quite efficient and transparent so far. The advantage I have here is that I am checking the process explicitly before starting it again. This wouldn't cause much overhead to the CPU on the server. Also you don't have to explicitly place the file into the startup folders.
function CheckNodeService ()
{
$node = Get-Process node -ErrorAction SilentlyContinue
if($node)
{
echo 'Node Running'
}
else
{
echo 'Node not Running'
Start-Process "C:\Program Files\nodejs\node.exe" -ArgumentList "app.js" -WorkingDirectory "E:\MyApplication"
echo 'Node started'
}
}
CheckNodeService
Simply use this, install, run and save current process list
https://www.npmjs.com/package/pm2-windows-startup
By my exp., after restart server, need to logon, in order to trigger the auto startup.
Need to create a batch file inside project folder.
Write this code in batch file
#echo off
start npm start
save batch file with myprojectname.bat
Go to run command and press window + R
Enter this command :- shell:common startup
Press ok then folder will be open.
Folder path like as C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
You will be paste your myprojectname.bat file.
You can check also. Need to system restart.
Copied directly from this answer:
You could write a script in any language you want to automate this (even using nodejs) and then just install a shortcut to that script in the user's %appdata%\Microsoft\Windows\Start Menu\Programs\Startup folder

Is there a more effective way to run a node.js file at startup? (Windows) [duplicate]

I have downloaded node.js executable. How can I run that executable as windows service?
I cannot use standard node.js installer, since I need to run multiple version of node.js concurrently.
Late to the party, but node-windows will do the trick too.
It also has system logging built in.
There is an API to create scripts from code, i.e.
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'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
FD: I'm the author of this module.
I found the thing so useful that I built an even easier to use wrapper around it (npm, github).
Installing it:
npm install -g qckwinsvc
Installing your service:
qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed
Uninstalling your service:
qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled
WinSer is a node.js friendly wrapper around the popular NSSM (Non-Sucking Service Manager)
From this blog
Next up, I wanted to host node as a service, just like IIS. This way
it’d start up with my machine, run in the background, restart
automatically if it crashes and so forth.
This is where nssm, the non-sucking service manager, enters the
picture. This tool lets you host a normal .exe as a Windows service.
Here are the commands I used to setup an instance of the your node
application as a service, open your cmd like administrator and type
following commands:
nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js
net start service_name
I'm not addressing the question directly, but providing an alternative that might also meet your requirement in a more node.js fashion way.
Functionally the requirements are:
Have the logic (app) running in the background
Be able to start/stop the logic
Automatically start the logic when system boots up
These requirements can be satisfied by using a process manager (PM) and making the process manager start on system startup. Two good PMs that are Windows-friendly are:
PM2
forever
To make the PM start automatically, the most simple way is to create a scheduled task with a "At Startup" trigger:
Since qckwinsvc has not been updated for a while there's a new version called qckwinsvc2 (npm, github)
It now supports args passed to the service. It also keeps a local cache so you don't have to provide a path every time you want to perform an action
Use the now arg to start the service as soon as it's installed
qckwinsvc2 install name="Hello" description="Hello World" path="C:\index.js" args="--y" now
qckwinsvc2 uninstall name="Hello"
qckwinsvc2 list
The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.
Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run
serman install <path_to_config_file>
will install the service. stdout and stderr are all logged. For more info, take a look at the project website.
A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.
<service>
<id>hello</id>
<name>hello</name>
<description>This service runs the hello application</description>
<executable>node.exe</executable>
<!--
{{dir}} will be expanded to the containing directory of your
config file, which is normally where your executable locates
-->
<arguments>"{{dir}}\hello.js"</arguments>
<logmode>rotate</logmode>
<!-- OPTIONAL FEATURE:
NODE_ENV=production will be an environment variable
available to your application, but not visible outside
of your application
-->
<env name="NODE_ENV" value="production"/>
<!-- OPTIONAL FEATURE:
FOO_SERVICE_PORT=8989 will be persisted as an environment
variable machine-wide.
-->
<persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>
https://nssm.cc/ service helper good for create windows service by batch file
i use from nssm & good working for any app & any file

How to install node.js as windows service?

I have downloaded node.js executable. How can I run that executable as windows service?
I cannot use standard node.js installer, since I need to run multiple version of node.js concurrently.
Late to the party, but node-windows will do the trick too.
It also has system logging built in.
There is an API to create scripts from code, i.e.
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'
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
FD: I'm the author of this module.
I found the thing so useful that I built an even easier to use wrapper around it (npm, github).
Installing it:
npm install -g qckwinsvc
Installing your service:
qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed
Uninstalling your service:
qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled
WinSer is a node.js friendly wrapper around the popular NSSM (Non-Sucking Service Manager)
From this blog
Next up, I wanted to host node as a service, just like IIS. This way
it’d start up with my machine, run in the background, restart
automatically if it crashes and so forth.
This is where nssm, the non-sucking service manager, enters the
picture. This tool lets you host a normal .exe as a Windows service.
Here are the commands I used to setup an instance of the your node
application as a service, open your cmd like administrator and type
following commands:
nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js
net start service_name
I'm not addressing the question directly, but providing an alternative that might also meet your requirement in a more node.js fashion way.
Functionally the requirements are:
Have the logic (app) running in the background
Be able to start/stop the logic
Automatically start the logic when system boots up
These requirements can be satisfied by using a process manager (PM) and making the process manager start on system startup. Two good PMs that are Windows-friendly are:
PM2
forever
To make the PM start automatically, the most simple way is to create a scheduled task with a "At Startup" trigger:
Since qckwinsvc has not been updated for a while there's a new version called qckwinsvc2 (npm, github)
It now supports args passed to the service. It also keeps a local cache so you don't have to provide a path every time you want to perform an action
Use the now arg to start the service as soon as it's installed
qckwinsvc2 install name="Hello" description="Hello World" path="C:\index.js" args="--y" now
qckwinsvc2 uninstall name="Hello"
qckwinsvc2 list
The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.
Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run
serman install <path_to_config_file>
will install the service. stdout and stderr are all logged. For more info, take a look at the project website.
A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.
<service>
<id>hello</id>
<name>hello</name>
<description>This service runs the hello application</description>
<executable>node.exe</executable>
<!--
{{dir}} will be expanded to the containing directory of your
config file, which is normally where your executable locates
-->
<arguments>"{{dir}}\hello.js"</arguments>
<logmode>rotate</logmode>
<!-- OPTIONAL FEATURE:
NODE_ENV=production will be an environment variable
available to your application, but not visible outside
of your application
-->
<env name="NODE_ENV" value="production"/>
<!-- OPTIONAL FEATURE:
FOO_SERVICE_PORT=8989 will be persisted as an environment
variable machine-wide.
-->
<persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>
https://nssm.cc/ service helper good for create windows service by batch file
i use from nssm & good working for any app & any file

Resources