L
L
LocKing2014-04-11 16:49:46
Node.js
LocKing, 2014-04-11 16:49:46

Why does a NodeJS application close after exiting the console?

I'm just starting to learn NodeJS and ran into an incomprehensible situation:
There is CentOS 6.4 with NodeJS installed.
Everything works fine, but after I run any js file through node, which "listens" on ports and processes requests to the server, and then I close the console, the script stops working.
Those. when the console is open, everything works, as soon as I do at least CTR + C or completely close the console, then everything collapses and I can again safely run the same script that just now worked with the command "node script_name.js" and it will start working again , but only until I want to close the console.
Is this normal NodeJS behavior?
How to start a web server correctly?
Perhaps the problem lies in the NodeJS settings?
Below is the actual code :)

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080, 'IP СЕРВЕРА');
console.log('Server running at http://IP СЕРВЕРА:8080/');

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
YoungSkipper, 2014-04-11
@LocKing

Short and not very correct answer run like this
Longer answer

apt-get install upstart // yum here for Centos
------
#!upstart
description "my app"

start on started mountall
stop on shutdown

# Automatically Respawn:
respawn
respawn limit 99 5

env NODE_ENV=production

exec node /somepath/myapp/app.js >> /var/log/myapp.log 2>&1
----

Use
sudo start myapp
sudo stop myapp
sudo restart myapp

Third node-style option
$npm install forever -g
$forever start app.js

S
Sergey, 2014-04-11
Protko @Fesor

Yes, this is normal behavior. How else would you like it? If you want the server to hang even after your session ends, you need to run your script as a daemon.
Read about deploying node.js projects.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question