Node.js server automatically start - node.js

I'm new to Node.js but willing to give it a serious try. Coming from PHP things seem a bit confusing as there is no index.php, but a start-script needs to be executed to fire up the server npm start.
How is this done in production? Are there pre-run scripts? What if the server closes for some reason, how do I get it back up automatically without having connection problems for the clients? Will it automatically work for the domain, or does it also mean someone alwasy has to go to domain.com:3000?
Ar am I thinking about this the wrong way?

What you are asking is very broad in term of question . Let me give the idea how it work.
Coming from PHP things seem a bit confusing as there is no
index.php, but a start-script needs to be executed to fire up the
server npm start.
So in node.js we have a file by which we start our node server and that we decide what we want . mostly people use app.js , server.js , index.js
when you run npm start , that means you would have package.json in the folder that file have written start: node app.js . And when you run npm start , it get fire .
How is this done in production? Are there pre-run scripts?
NODE_ENV=production npm start , you can access this in node code like this
process.env.NODE_ENV . in this way you can add dev,qa tag for each environment .
I will recommend you to have a look in
http://pm2.keymetrics.io/
What if the server closes for some reason, how do I get it back up automatically without having connection problems for the clients?
For that reason you can look at https://nodejs.org/api/cluster.html
You can manage the crash thread and then open another thread as node is single thread.
Also you can manage the node.js all type of error By this . This make node.js catch all exception and error
https://nodejs.org/api/process.html
process.on
does it also mean someone alwasy has to go to domain.com:3000?
No. You can take any port you want . 80,8080 whatever . I will recommend to use nginx in front of node.js application . But for less compatibility go for simple node application .
for example:-
var http = require('http');
var port = 3000 ; // take any 80, 8080
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : '*'
});
response.end('Hello World\n');
}).listen(port);
Hope this help .

Answering you 1st question there are other options how you can run node application. I suggest that you start using some packages likeNodemon
which are actually built for this purpose.
Answering your second question, you can use same for production deployments using some container system if you like. here are some optionsdocker, kubarnetees,and many more.
Your automatic restart thing can be solve either by you container manager or package you have used for deployment.
And for redirecting all request coming on 80 or 443 port that you want to redirect to your application you can try nginx.

There are some modules which you can use to restart the server automatically if it closes for some reason. Some of them are pm2, forever.

Without going into much detail, you have to be VERY clear of the following:
Your node web process will die. Yes, that's right, when there is an uncaught exception it can die. Therefore, you need more than one process for failover, and for that there are many techniques and libraries. Some of them are:
Several node processes load balanced behind a web server (nginx most commonly used)
Managed cluster of node processes (https://github.com/Unitech/pm2)
Or (not that good for production in my opinion) some process monitor which will restart your node web process if it dies:
https://github.com/foreverjs/forever

Related

Run two app on same server or on same port

I have MEAN stack apps, I want a suggestion about to run both them on the same server or on the same port(suggestion which one is better).I found article about to run server on the same port using proxies,also I want to know is this a good idea.There is some troubles about running on same server,because I'm using Angular 6 as Front-end, I have to build those files into my node's (which is one in this case) public folder,so I think that's impossible (I think), because there must be index.html and it must be one and not only index.html, other files too. And if this two cases is not good deal.please just let me know about that.Thanks for help and thanks for attention.

What is sense of NodeJS modules without any exports?

If there's any. Im not really into web technologies, but have to understand some awful code written by someone else in Node.
All node.js apps are npm modules once you execute npm init. After that point, you can publish the module by executing npm publish assuming you gave it a unique name in the package.json.
If the app isn't meant to return anything, then there is no need to export anything. However, it's almost always worth exporting something to allow for unit testing deeper than just starting the app as an http server and sending it requests.
It is also sometimes useful to modify the way your app runs based on whether it is being required as a module or executed as an app. For example, say i have an express rest api server. I can run it as a standalone server on api.example.com, and then require it into another application and run it from that application directly to avoid CORS issues without having to duplicate code or deal with git submodules, instead I simply npm install the api into the application that needs it and attach it just like you would a router. www.example.com/api
app.use('/api', require('#myusername/api.example.com'))

restart nodejs server programmatically

User case:
My nodejs server start with a configuration wizard that allow user to change the port and scheme. Even more, update the express routes
Question:
Is it possible to apply the such kind of configuration changes on the fly? restart the server can definitely bring all the changes online but i'm not sure how to trigger it from code.
Changing core configuration on the fly is rarely practiced. Node.js and most http frameworks do not support it neither at this point.
Modifying configuration and then restarting the server is completley valid solution and I suggest you to use it.
To restart server programatically you have to execute logics outside of the node.js, so that this process can continue once node.js process is killed. Granted you are running node.js server on Linux, the Bash script sounds like the best tool available for you.
Implementation will look something like this:
Client presses a switch somewhere on your site powered by node.js
Node.js then executes some JavaScript code which instructs your OS to execute some bash script, lets say it is script.sh
script.sh restarts node.js
Done
If any of the steps is difficult, ask about it. Though step 1 is something you are likely handling yourself already.
I know this question was asked a long time ago but since I ran into this problem I will share what I ended up doing.
For my problem I needed to restart the server since the user is allowed to change the port on their website. What I ended up doing is wrapping the whole server creation (https.createServer/server.listen) into a function called startServer(port). I would call this function at the end of the file with a default port. The user would change port by accessing endpoint /changePort?port=3000. That endpoint would call another function called restartServer(server,res,port) which would then call the startServer(port) with the new port then redirect user to that new site with the new port.
Much better than restarting the whole nodejs process.

start a new node.js Server from an existing one

I haven't found out anything about my problem so I'd like to ask you if following problem could be solved. I have a nodejs server which displays a website with a button. Is it possible to start another node server (which should do some spookyJS tests and print the results to the website) when i click this button?
I found out that with nowJS you have a shared space which the server and "client" (some html page) share. Is this module helpful?
Thanks for your help,
Alex
In short - Yes!
But perhaps you can have both web servers running at all times. In fact, it'll be less of a load on your hardware.
1st Server - Application Server - runs at yoursite.com
2nd Server - SpookyJs/Test Server - runs at tests.yoursite.com
After the servers are up and running the next thing I'd do is wrap the SpookyJs application with a simple restful interface/api. To start tests and to respond with the result of a test.
An important thing to note here is that when you start the SpookyJS application, let stay open. So that every request to the SpookyJS application (through your interface) calls the "open" or the "then" method.
Again, this is to remedy the issue of spawning too many headless browsers.
After the request goes through, go ahead and respond to the request with the result that spooky gives you.
Maybe that helps?
We are doing similar things with Zombie js... so maybe it will help you (:

How can I deploy a Node.js application?

Node.js is "JavaScript on the server". OK. But, how can I "deploy" a Node.js application? Which kind of web server should I use? How can I create "Controllers"? And how can I persist data in a DB? Thanks in advance.
This is one of the best places to get familiar with what's currently available: https://github.com/joyent/node/wiki/modules.
Regarding "which kind of web server" you should use, it depends on what you're trying to build. I currently use express, which I've been very happy with.
For database connectivity, that depends on what type of database you're connecting to. For MongoDB, I use Mongoose, and for CouchDB I just use a raw HTTP client. If you need MySQL, the most popular one right now seems to be node-mysql. There are lots of other database drivers here.
Given the high-level nature of your question, it sounds like you might be better profited by some "getting started" guides, to really get familiar with what node.js is. There are several good articles here, for example. From there you can move into web servers and database drivers more comfortably.
There are many deployment solutions available, CloudFoundry being one of them. I think you need a great understanding of how Node works first though. Basically, to "deploy" an application, you would typically send the files over to the server and run it from the commandline:
node server.js
There is no web server involved like Apache or nginx. If your application needs a web server, there are some solutions in Node like Express.
Databases work as usual. You install one over to your server, use one of the many Node modules to connect to it and write data. It's separate from your Node server.
Check out this excellent list of Node modules from the GitHub wiki.
You should start by looking at http://nodejs.org. Great place to find information when writing code. There are a lot of modules that you can use or you can start from scratch and work your way up.
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/');
Easiest example of an web server written in node.

Resources