Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run node js file in background process on window server?

I was creating a node.js project and uploaded it to my Windows server to provide an API service for mobile application.

When I open command prompt and type

node app.js

It runs correctly, but when I close the command prompt my node.js server stopped running.

How to make it still running when I close the commend prompt?

For example on Ubuntu I use the command

nohup 

How can I do this on Windows?

like image 245
Dara Vichit Avatar asked Oct 06 '16 04:10

Dara Vichit


People also ask

How do you run a NodeJS file on a server?

The usual way to run a Node. js program is to run the globally available node command (once you install Node. js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.

How do I run a NodeJS application as a Windows service?

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.

How do I permanently run NodeJS server?

js application locally after closing the terminal or Application, to run the nodeJS application permanently. We use NPM modules such as forever or PM2 to ensure that a given script runs continuously. NPM is a Default Package manager for Node.


2 Answers

You can make the process run in background using pm2

pm2 start app.js --watch

This will start the process and will also look for changes in the file. More about watch flag

like image 198
Himani Agrawal Avatar answered Oct 27 '22 01:10

Himani Agrawal


Nodemon #ftw. On Windows, Forever doesn't really watch files so much as casually observe them, while pm2 restarts the server every time you load a page.

Each of these tools works similarly, and each installs just as in the accepted answer. E.g.:

npm install nodemon -g

This installs nodemon globally, and to use you can simply navigate to your project folder and enter:

nodemon

(Assuming your project has an app.js file). You can add the -w switch, just as in Forever and pm2, however if you're just wanting to watch all files, you can omit that. To run nodemon in the background with Forever, you would run this:

forever nodemon --exitcrash 

Nodemon is good for development, especially on Windows, while Forever and pm2 are more for production, on Linux.

like image 27
josebrwn Avatar answered Oct 27 '22 00:10

josebrwn