Stopping nodejs process start by npm? - node.js

I am in the process of creating some scripts to deploy my node.js based application, via continuous integration and I am having trouble seeing the right way to stop the node process.
I start the application via a start-dev.sh script:
#!/bin/sh
scripts_dir=`dirname $0`
cd "${scripts_dir}/"..
npm start &
echo $! > app.pid
And then I was hoping to stop it via:
#!/bin/sh
scripts_dir=`dirname $0`
cd "${scripts_dir}/"..
echo killing pid `cat app.pid`
kill -9 `cat app.pid`
The issue I am finding is that npm is no longer running at this point, so the pid isn't useful to stop the process tree. The only workaround I can think of at this point is to skip npm completely for launch and simply call node directly?
Can anyone suggest an appropriate way to deal with this? Is foregoing npm for launching a good approach, in this context?

Forever can do the process management stuff for you.
forever start app.js
forever stop app.js
Try to avoid relying on npm start outside of development, it just adds an additional layer between you and node.

just use supervisor example conf is like
[program:long_script]
command=/usr/bin/node SOURCE_FOLDER/EXECUTABLE_JAVASCRIPT_FILE.js
autostart=true
autorestart=true
stderr_logfile=/var/log/long.err.log
stdout_logfile=/var/log/long.out.log
where
SOURCE_FOLDER is the folder for your project
EXECUTABLE_JAVASCRIPT_FILE the file to be run
you can check the post here

Related

Bash script stuck after e2e tests run

I'm running my e2e tests with Nightwatch.js. I want them to run with a bash script (with the end result of them running in CI).
I am pretty new to bash and here is what i have so far:
#!/bin/bash
# exit on errors
set -e
export NODE_ENV=development
export LIVERELOAD_DISABLED=YES
npm install
NODE_ENV=e2e grunt build
echo "...Starting Node App"
#start app in the background
NODE_ENV=e2e node server.js &
#save node app process id
NODE_PROC=$!
#wait a bit
sleep 10
echo "...Running Frontend Tests"
NODE_ENV=e2e npm run nightwatch
echo "...Tests Finished... Killing Node App"
kill -9 $NODE_PROC
echo "...Node App Killed"
the problem is that the script gets stuck after running all the tests (line: NODE_ENV=e2e npm run nightwatch)
the only output i'm getting are the logs and the usual tests output. The script gets stuck no matter if the tests pass, fail, or some do and some don't.
I've tried adding exit 0 at the end which didn't work (makes sense, since it doesn't execute to that point).
Also, changing set -e to set -ex didn't change the output.
what am i missing here?
So i was looking in the wrong place, the script is completely fine, the issue was that i did not close the connection to the DB inside the tests.
Not sure why that caused the issue, but it fixed it

How to use pm2 with a nodejs app that uses readline for taking command line input?

I have a Node.js app that uses the node's native readline to be able to take command-line inputs.
When launching the app with pm2, the command-line input is unavailable.
Any ideas how to solve this issue? Other than using systemd and creating an init script myself?
Use pm2 to attach to your process and you will see readline, clearline and cursorTo working as expected.
First get your process id with:
$ pm2 id {your-process-name}
[ 7 ]
Let's say it's 7:
$ pm2 attach 7
if you check the pm2 website they clearly mention the following line: Advanced, production process manager for Node.js. So using it in this context is unnecessary as all pm2 does is start your 'node' process and allows you to manage it, the simple way is to use command line args while starting the process.
for example:
I myself use commander for this purpose. it manages all my command line arguments (u can see its usage). and with pm2 i use it like following:
pm2 start server.js --name production -- --env dev -p 3458
notice -- before --env, it is used to separate pm2 arguments from the arguments you want to supply to your process
p.s.
PM2 has more complex usage than this, in the terms of process management, i myself use it for production level deployment. If you want to take input from a user every time s/he starts your app, then you should stick with using node command only

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

How set upstart correctly for a node.js app

I am using an amazon ec2 instance with ubuntu to host my node.js application, i already made all the configurations, and is working good when i type:
nodemon ./bin/www
./bin/www is the file that creates the server.
Now, i am trying to setup the upstart, and i follow a tutorial, this is my configuration file:
path:
/etc/init/photogrid.conf:
inside:
description "Photogrid"
start on started mountall
stop on shutdown
respawn
respawn limit 99 5
env NODE_ENV=production
exec node /home/ubuntu/photogrid/bin/www >> /var/log/photogrid.log 2>&1
But when i try to access the site, is showing:
Cannot GET /
I follow a tutorial, and the only difference between my configuration file is this part:
Original:
exec node /home/ubuntu/photogrid/app.js >> /var/log/photogrid.log 2>&1
My one:
exec node /home/ubuntu/photogrid/bin/www >> /var/log/photogrid.log 2>&1
Start with upstart:
Start with nodemon bin/www:
In my logs i see the following when i try access the home '/':
^[[0mGET / ^[[33m404 ^[[0m12.036 ms - 13^[[0m
It seems that you need to switch to correct directory before launching exec. Maybe this will resolve your error:
description "Photogrid"
start on filesystem and started networking
stop on shutdown
respawn
respawn limit 99 5
env NODE_ENV=production
script
export HOME="/home/ubuntu/photogrid"
cd $HOME
exec node /home/ubuntu/photogrid/bin/www >> /var/log/photogrid.log 2>&1
end script
Try adding chdir /home/ubuntu/photogrid to your upstart config. Also, interactively in a terminal try: NODE_ENV=production nodemon ./bin/www. Perhaps you are using app.configure where you shouldn't be?

Nodejs/Strongloop: working upstart config example

After update strongloop to v2.10 slc stops writing logs.
Also I couldn't make the app to start in production mode.
/etc/init/app.conf
#!upstart
description "StrongLoop app"
start on startup
stop on shutdown
env NODE_ENV=production
script
exec slc run /home/ubuntu/app/ \
-l /home/ubuntu/app/app.log \
-p /var/run/app.pid
end script
Can anybody check my upstart config or provide another working copy?
Are you were writing the pid to a file so that you can use it to send SIGUSR2 to the process to trigger log re-opening from logrotate?
Assuming you are using Upstart 1.4+ (Ubuntu 12.04 or newer), then you would be better off letting slc run log to its stdout and let Upstart take care of writing it to a file so that log rotation is done for you:
#!upstart
description "StrongLoop app"
start on startup
stop on shutdown
# assuming this is /etc/init/app.conf,
# stdout+stderr logged to: /var/log/upstart/app.log
console log
env NODE_ENV=production
exec /usr/local/bin/slc run --cluster=CPUs /home/ubuntu/app
The log rotation for "free" is nice, but the biggest benefit to this approach is Upstart can log errors that slc run reports even if they are a crash while trying to set up its internal logging, which makes debugging a lot easier.
Aside from what it means to your actual application, the only effect NODE_ENV has on slc run is to set the default number of cluster workers to the number of detected CPU cores, which literally translates to --cluster=CPUs.
Another problem I find is the node/npm path prefix not being in the $PATH as used by Upstart, so I normally put the full paths for executables in my Upstart jobs.
Service Installer
You could also try using strong-service-install, which is a module used by slc pm-install to install strong-pm as an OS service:
$ npm install -g strong-service-install
$ sudo sl-svc-install --name app --user ubuntu --cwd /home/ubuntu/app -- slc run --cluster=CPUs .
Note the spaces around the -- before slc run

Resources